I am trying to write an interface for a motorised stage. What I am trying to do is to create a scan feature such that the motor will move a certain distance, stop and wait a specified time and then move the same distance again. It will repeat the process until it has reached the total length specified by the user. To do this I am trying to use a Timer class features as I still want the GUI to be active during the scan.
I've got some idea of how to code it but get stuck. It would go something like:
private void btnGo_Click(object sender, EventArgs e) //On click
{
int i = 0;
int stop = 15; //number of times I want the motor to stop
System.Timers.Timer bTimer; //initialise timer
bTimer = new System.Timers.Timer(waittime); //time I want the motor to wait
bTimer.Elapsed += PerformMove;
bTimer.Enabled = true;
if(i==stop){bTimer.stop()}
}
private void PerformMove(Object source, ElapsedEventArgs e) //event to move motor
{
//movemotor
i++;
}
Not being particularly familiar with C# or timers is undoubtedly the cause of my confusion. What's the best way to approach this problem? Any example code would be great.
If somebody could clarify what the lines
bTimer.Elapsed += PerformMove;
bTimer.Enabled = true;
actually do too that would also be of great use!
EDIT (sorry, didn't think this was a key part): The value of stop is defined upon the user click of the button from a text box within the GUI. i.e.
int stop = Convert.ToDouble(tbIntervalStops.Text); //grab integer from user input upon button click
This would be the correct solution without memory leak
private int i = 0;
private int stop = 15; //number of times I want the motor to stop
private Timer bTimer; //initialise timer -> Thats wrong: nothing is INITIALIZED here its just defined
private void btnGo_Click(object sender, EventArgs e) //On click
{
i = 0;
stop = Convert.ToInt32(tbIntervalStops.Text); //using int because double is a floating point number like 12.34 and for counting only full numbers will be needed
bTimer = new System.Timers.Timer(waittime); //time I want the motor to wait + Here the Timer is INITIALIZED
bTimer.Elapsed += PerformMove; //Adds the Eventhandler, What should be called when the time is over
bTimer.Enabled = true; //This starts the timer. It enables running like pressing the start button on a stopwatch
}
private void PerformMove(Object source, ElapsedEventArgs e) //event to move motor
{
//movemotor
i++;
if (i == stop) //if stop would be a double here we will have the danger to get not a true because of rounding problems
{
bTimer.Stop();
//now enable the Garbage Collector to remove the Timer instance
bTimer.Elapsed -= PerformMove; //This removes the Eventhandler
bTimer.Dispose(); //This frees all resources held by the Timer instance.
bTimer = null;
}
}
Alternatively, you could also derive from the System.Timers.Timer object and create a wrapper which has properties specific to the task. In which case, you would simply need to instantiate a MoveTimer and subscribe to it's OnPerformMoveEvent.
Update: Added OnMovesCompletedEvent
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace TimerExample
{
public class MoveTimer : System.Timers.Timer
{
public event EventHandler OnPerformMoveEvent = delegate { };
public event EventHandler OnMovesCompletedEvent = delegate { };
public MoveTimer()
{
Initialize(new TimeSpan(), 0);
}
public MoveTimer(TimeSpan wait, int moves)
{
this.Initialize(wait, moves);
}
private int _i;
private int _totalmoves;
public int Moves
{
get { return this._totalmoves; }
set { this._totalmoves = value; }
}
private TimeSpan _wait;
public TimeSpan Wait
{
get { return this._wait; }
set { this._wait = value; }
}
private System.Timers.Timer _timer;
private void Initialize(TimeSpan wait, int moves)
{
this._totalmoves = moves;
this._wait = wait;
this._timer = new System.Timers.Timer(wait.Milliseconds);
}
private void BindComponents()
{
this._timer.Elapsed += _timer_Elapsed;
}
private void UnBindComponents()
{
this._timer.Elapsed -= _timer_Elapsed;
}
public void StartTimer()
{
this._timer.Enabled = true;
}
public void StopTimer()
{
this._timer.Enabled = false;
}
void _timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
this._i++;
if (this.OnPerformMoveEvent != null)
this.OnPerformMoveEvent(this, EventArgs.Empty);
if (this._i == this._totalmoves)
{
this._timer.Stop();
this.UnBindComponents();
this.Dispose();
if (this.OnMovesCompletedEvent != null)
this.OnMovesCompletedEvent(this, EventArgs.Empty);
}
}
}
}
In regards to the user input where the number of moves or stops is provided as a string. I would handle this outside of the MoveTimer object. Validation should always be performed.
First determine that the value can be parsed into an integer. If not, throw an exception to let the user know that the input was entered incorrectly.
To use the above, something like the following would be all it requires:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace TimerExample
{
class Program
{
static void Main(string[] args)
{
//Create move timer that will trigger 15 times, once every 30 seconds.
MoveTimer moveTimer = new MoveTimer(new TimeSpan(0, 0, 30), 15);
//Substribe to the move timer events
moveTimer.OnPerformMoveEvent += moveTimer_OnPerformMoveEvent;
moveTimer.OnMovesCompletedEvent += moveTimer_OnMovesCompletedEvent;
//Start the timer
moveTimer.StartTimer();
//What happens in between the moves performed?
}
static void moveTimer_OnMovesCompletedEvent(object sender, EventArgs e)
{
//All the moves have been performed, what would you like to happen? Eg. Beep or tell the user.
}
static void moveTimer_OnPerformMoveEvent(object sender, EventArgs e)
{
//Timer has lapsed, what needs to be done when a move is requested?
}
}
}
Related
I am writing up a C# application using Winforms, and I need to collect some data based on my selection from a comboBox. I also have a start button that enables data collection, and a stop button that halts the data collection.
This is what I am capable of doing right now:
Measure all data from all channels by switching my selection on the comboBox (one channel at a time). The process goes like: select a channel- start button click - wait for data collection - stop button click
But here is what I want to do in code:
Select a channel - start button click - wait for data collection - stop button click
switch to next channel - start button click -wait for data collection - stop button click
................
repeat this process until done.
My question is: what should I adopt to achieve this?
I have been trying to use startButton.PerformClick( ) to enabling the buttons, however, I need to stop for a few seconds in between starting and stopping to wait for data collection.
You may ask why because this is very inefficient, but for some reason the DLL from the third party cannot collect data from all channels at the same time. So i have to manually switch my channel selection from the comboBox in order to collect all data at one go.
Please let me know if you have any suggestions.
private void timer_Tick(object sender, EventArgs e)
{
startButton.PerformClick();
}
private void timer2_Tick(object sender, EventArgs e)
{
stopButton.PerformClick();
}
private void checkAll_CheckedChanged(object sender, EventArgs e)
{
int i = 0;
while (i != 40) //there are a total of 40 channels
{
System.Windows.Forms.Timer mytimer = new System.Windows.Forms.Timer();
mytimer.Interval = 5000;
System.Windows.Forms.Timer mytimer2 = new System.Windows.Forms.Timer();
mytimer2.Interval = 7000;
mytimer.Start();
mytimer.Tick += new EventHandler(timer_Tick);
mytimer2.Start();
mytimer2.Tick += new EventHandler(timer2_Tick);
physicalChannelComboBox.SelectedIndex = i;
i++;
Thread.Sleep(5000);
}
}
Here is a simple routine shell that should help you. This uses a timer to poll if the data is complete (checking a boolean, which is currently set to true for testing). In your case you could probably just set the timers tick value to be the delay you want. If you have a way of knowing when the data is done being collected for the channel, that would be more preferable. This code runs standalone so you can test and configure it before starting to integrate it into your existing code. All it requires is a a listbox for viewing the logs.
public partial class DataCollectorForm : Form
{
private Timer timer = new Timer();
private int numberOfChannels = 40;
private int currentChannelNumber = 0;
private DateTime routineStartTime;
private DateTime routineStopTime;
private DateTime channelStartTime;
private DateTime channelStopTime;
public DataCollectorForm()
{
InitializeComponent();
timer.Interval = 250;
timer.Tick += Timer_Tick;
DataCollectionRoutineStart();
}
private void Timer_Tick(object sender, EventArgs e)
{
// Need to check if data collection for this channel is complete..
//
var isDoneCollectingData = true;
if (isDoneCollectingData)
{
ChannelDataCollectionStop();
currentChannelNumber++;
if (currentChannelNumber >= numberOfChannels)
{
DataCollectionRoutineComplete();
}
else
{
ChannelDataCollectionStart();
}
}
}
public void DataCollectionRoutineStart()
{
routineStartTime = DateTime.Now;
Log("Data Collection Routine Start");
currentChannelNumber = 0;
ChannelDataCollectionStart();
timer.Start();
}
private void ChannelDataCollectionStart()
{
channelStartTime = DateTime.Now;
Log("Data Collection Start : channel " + currentChannelNumber);
}
private void ChannelDataCollectionStop()
{
channelStopTime = DateTime.Now;
Log("Data Collection Stop : channel " + currentChannelNumber + " : elapsed " + (channelStopTime - channelStartTime));
}
private void DataCollectionRoutineComplete()
{
routineStopTime = DateTime.Now;
timer.Stop();
Log("Data Collection Routine Complete : elapsed " + (routineStopTime - routineStartTime));
}
private void Log(string msg)
{
loggingListBox.Items.Add(msg);
}
}
This is my requirement I have to use while loop inside timer, after launch application after click on button UI is locked not able to move and text is not diplaying at textbox too
below is the code
using System;
using System.Windows.Forms;
namespace WinScreenLocked
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
int Number = 0;
private void timer1_Tick(object sender, EventArgs e)
{
while (true)
{
textBox1.Text = Number.ToString();
Number++;
}
}
private void button1_Click(object sender, EventArgs e)
{
timer1.Start();
}
}
}
// Create a 30 min timer
timer = new System.Timers.Timer(1800000);
// Hook up the Elapsed event for the timer.
timer.Elapsed += OnTimedEvent;
timer.Enabled = true;
private static void OnTimedEvent(object source, ElapsedEventArgs e)
{
// do stuff
}
with the usual caveats of: timer won't be hugely accurate and might need to GC.KeepAlive(timer)
See also: Why does a System.Timers.Timer survive GC but not System.Threading.Timer?
you can stop the thread to block the ui i.e using
System.Threading.Thread.Sleep(2000);
it takes miliseconds in above 2000 miliseconds is equal to 2 seconds.
Seeing as this is winforms you can use Application.DoEvents() to process the UI refresh.
See this : https://social.msdn.microsoft.com/Forums/en-US/b1b1969d-8a51-496c-9274-a0ac1708a8b4/what-does-applicationdoevents-actually-do?forum=csharplanguage
I have a button with mouse click event handlers.
When the button is pressed (mouse down), a timer is started to simulate other clicks with a delay. The click runs a bitmap transformation, e.g. rotation of 0.5 each time.
When the button is released (mouse up), the timer is stopped.
Code in Button class :
private void TreatMouseDown(object sender, MouseEventArgs e) {
// Following clicks
_repeteTimer.Tick += (senderTick, eTick) => {
_repeteTimer.Stop();
PerformClick();
_repeteTimer.Interval = _nextDelay;
_repeteTimer.Start();
};
// First click
PerformClick();
_repeteTimer.Interval = _firstDelay;
_repeteTimer.Start();
}
private void TreatMouseUp(object sender, MouseEventArgs e) {
_repeteTimer.Stop();
}
Code in window :
btnRotation1.Click += (sender, e) => PHOTO_Treat(1);
private void PHOTO_Treat(int delta) {
if (!_inProgress) {
_photoRotation += delta * 0.5F;
PHOTO_Show();
}
}
private void PHOTO_Show(){
if (_inProgress) return;
_inProgress= true;
// Make image treatments ...
_inProgress = false;
}
The problem is that several transformations occur again after the button is released, if the transformation take long time.
How can I suppress remaining ?
Sounds like you have some serious threading issues.
You could check whether the button is still down by checking _repeteTimer.Enabled.
Also, add a lock. Even if just to be safe.
private readonly object SyncRoot = new object();
private void PHOTO_Show()
{
if (!_inProgress)
{
// race for a lock
lock (SyncRoot)
{
// check button state
if (!_repeteTimer.Enabled)
{
// button was released
return;
}
// else
try
{
_inProgress = true;
MakeImageTreatments();
}
finally
{
_inProgress = false;
}
}
}
}
Is there any way to capture the time interval between mouse wheel scroll start and stop? Actually I want to capture the interval between the scrolling start and stop when I very quickly scroll the mouse wheel.
I have already looked at MouseWheel event but it don't fulfill my requirement. In senes that it always gives a value of Delta 120 or -120 but i want to call a function depending on the speed of the mouse scroll for example when i scroll the mouse normally i want to perform function 1 and when i scrolled the mouse very quickly i want to perform the function 2. In other words is there any way to distinguish between the mouse scroll high and normal speed.
Any advice will be appreciated.
can't you capture the mouse wheel events and see how long between them. Basically start a timer when you get a mouse wheel event and then in the next event see what the timer is at (and so how long has elapsed between the events) to determine the speed the wheel is being turned at? If the elapsedtime is smaller than a certain threshold, perform function2 and if it is faster than a certain threshold perform function 1.
You will probably have to set it to perform function 1 if the timer goes off in case they only do a single scroll.
In fact you might be able to do it this way:
start a timer (with an interval that indicates slow mouse wheeling) in the mouse wheel event, then if the timer goes off perform function 1. If the mouse wheel event happens again before the timer has gone off then reset the timer and increment a counter (to keep track of the number in wheel events since you did stuff) then start a second (longer) timer. if the counter is greater then a certain threshold perform function 2. When the second timer elapses, reset the counter. Something along those lines should give you the ability to fire function 1 when slow wheel turning and function 2 when the wheel is rapidly turned through a few 'clicks'.
this code should give a (very dirty) indication of the sort of thing I was thinking of. After playing a little I'm not really sure it's a good solution though....
private void mouseWheelHandler (object sender, MouseEventArgs e)
{
slowTimer.Enabled = false;
slowTimer.Stop ();
slowTimer.Interval = 200;
slowTimer.Start();
slowTimer.Enabled = true;
m_counter++;
Trace.WriteLine(string.Format("counter={0}", m_counter));
if (fastTimer.Enabled==false)
{
fastTimer.Enabled = true;
fastTimer.Interval = 150;
fastTimer.Start ();
}
if (m_counter>5)
{
Trace.WriteLine("called method 2");
m_counter = 0;
fastTimer.Stop ();
slowTimer.Enabled = false;
slowCheckTimer.Stop ();
slowCheckTimer.Interval = 250;
slowCheckTimer.Start();
slowCheckTimer.Enabled = true;
}
}
private void slowTimer_Tick(object sender, EventArgs e)
{
Trace.WriteLine("slow timer ticked");
if (slowCheckTimer.Enabled==false)
{
Trace.WriteLine ("called method 1");
}
slowTimer.Enabled = false;
}
private void fastTimer_Tick(object sender, EventArgs e)
{
fastTimer.Enabled = false;
Trace.WriteLine("fast timer ticked");
m_counter = 0;
fastTimer.Stop ();
}
private void slowCheckTimer_Tick(object sender, EventArgs e)
{
Trace.WriteLine("slow check timer ticked");
slowCheckTimer.Stop ();
slowCheckTimer.Enabled = false;
}
Take a look at the Control.MouseWheel event.
As suggested by the Sam Holder i am posting here a modified verion of his advice to help other programmers facing the same problem.
public partial class Form1 : Form
{
int m_counter = 0;
public Form1()
{
InitializeComponent();
// Attach Mouse Wheel Event
this.MouseWheel += new MouseEventHandler(Form1_MouseWheel);
}
void Form1_MouseWheel(object sender, MouseEventArgs e)
{
// Refresh Slow Timer
slowTimer.Enabled = false;
slowTimer.Stop();
slowTimer.Interval = 150;
slowTimer.Start();
slowTimer.Enabled = true;
// Incremenet counter
m_counter++;
// Start Fast Timer
if (fastTimer.Enabled == false)
{
fastTimer.Enabled = true;
fastTimer.Interval = 50;
fastTimer.Start();
}
// If this returns true call
// the fast scroll implementation
if (m_counter > 4)
{
Console.WriteLine("Quick Method Called");
m_counter = 0;
fastTimer.Stop();
slowTimer.Enabled = false;
slowCheckTimer.Stop();
slowCheckTimer.Interval = 200;
slowCheckTimer.Start();
slowCheckTimer.Enabled = true;
}
}
private void slowTimer_Tick(object sender, EventArgs e)
{
if (slowCheckTimer.Enabled == false)
{
Console.WriteLine("Slow Method Called");
}
slowTimer.Enabled = false;
}
private void fastTimer_Tick(object sender, EventArgs e)
{
fastTimer.Enabled = false;
m_counter = 0;
fastTimer.Stop();
}
private void slowCheckTimer_Tick(object sender, EventArgs e)
{
slowCheckTimer.Stop();
slowCheckTimer.Enabled = false;
}
}
I wanted to make a simple Countdown-Application with C# to show as an example.
For the very first and basic version I use a Label to display the current time left in seconds and a Button to start the countdown. The Button's Click-Event is implemented like this:
private void ButtonStart_Click(object sender, RoutedEventArgs e)
{
_time = 60;
while (_time > 0)
{
_time--;
this.labelTime.Content = _time + "s";
System.Threading.Thread.Sleep(1000);
}
}
Now when the user clicks the Button the time is actually counted down (as the application freezes (due to Sleep())) for the chosen amount of time but the Label's context is not refreshed.
Am I doing something generally wrong (when it comes to Threads) or is it just a problem with the UI?
Thank you for your answers!
I now use a System.Windows.Threading.DispatcherTimer to do as you told me. Everything works fine so this question is officially answered ;)
For those who are interested: Here is my code (the essential parts)
public partial class WindowCountdown : Window
{
private int _time;
private DispatcherTimer _countdownTimer;
public WindowCountdown()
{
InitializeComponent();
_countdownTimer = new DispatcherTimer();
_countdownTimer.Interval = new TimeSpan(0,0,1);
_countdownTimer.Tick += new EventHandler(CountdownTimerStep);
}
private void ButtonStart_Click(object sender, RoutedEventArgs e)
{
_time = 10;
_countdownTimer.Start();
}
private void CountdownTimerStep(object sender, EventArgs e)
{
if (_time > 0)
{
_time--;
this.labelTime.Content = _time + "s";
}
else
_countdownTimer.Stop();
}
}
Yes, event handlers should not block - they should return immediately.
You should implement this by a Timer, BackgroundWorker or Thread (in this order of preference).
What you are seeing is the effect of a long-running message blocking the windows message queue/pump - which you more commonly associate with the white application screen and "not responding". Basically, if your thread is sleeping, it isn't responding to messages like "paint yourself". You need to make your change and yield control to the pump.
There are various ways of doing this (ripper234 does a good job of listing them). The bad way you'll often see is:
{ // your count/sleep loop
// bad code - don't do this:
Application.DoEvents();
System.Threading.Thread.Sleep(1000);
}
I mention this only to highlight what not to do; this causes a lot of problems with "re-entrancy" and general code management. A better way is simply to use a Timer, or for more complex code, a BackgroundWorker. Something like:
using System;
using System.Windows.Forms;
class MyForm : Form {
[STAThread]
static void Main() {
Application.EnableVisualStyles();
Application.Run(new MyForm());
}
Timer timer;
MyForm() {
timer = new Timer();
count = 10;
timer.Interval = 1000;
timer.Tick += timer_Tick;
timer.Start();
}
protected override void Dispose(bool disposing) {
if (disposing) {
timer.Dispose();
}
base.Dispose(disposing);
}
int count;
void timer_Tick(object sender, EventArgs e) {
Text = "Wait for " + count + " seconds...";
count--;
if (count == 0)
{
timer.Stop();
}
}
}