I am trying to delay events in my method by using a timer, however i do not necessarily understand how to use a timer to wait.
I set up my timer to be 2 seconds, but when i run this code the last call runs without a 2 second delay.
Timer timer = new Timer();
timer.Tick += new EventHandler(timer_Tick); // Everytime timer ticks, timer_Tick will be called
timer.Interval = (1000) * (2); // Timer will tick evert second
timer.Enabled = true; // Enable the timer
void timer_Tick(object sender, EventArgs e)
{
timer.Stop();
}
private void button1_Click(object sender, EventArgs e)
{
label1.Text = "first";
timer.Start();
label1.Text = "second";
}
So when i click my button, it immediately shows label1 as "second", as opposed to changing to "first", waiting 2 seconds, then changing to "second". I have read lots of threads here about using timers instead of thread.sleep, but i cannot seem to find/figure out how to actually implement that.
If you're using C# 5.0 await makes this much easier:
private async void button1_Click(object sender, EventArgs e)
{
label1.Text = "first";
await Task.Delay(2000);
label1.Text = "second";
}
timer.Start() just starts the timer but immediately returns while the timer is running in the background. So between setting the label text to first and to second there is nearly no pause. What you want to do is wait for the timer to tick and only then update the label again:
void timer_Tick(object sender, EventArgs e)
{
timer.Stop();
label1.Text = "second";
}
private void button1_Click(object sender, EventArgs e)
{
label1.Text = "first";
timer.Start();
}
Btw. you should not set timer.Enabled to true, you are already starting the timer using timer.Start().
As mentioned in the comments, you could put the timer creation into a method, like this (note: this is untested):
public void Delayed(int delay, Action action)
{
Timer timer = new Timer();
timer.Interval = delay;
timer.Tick += (s, e) => {
action();
timer.Stop();
};
timer.Start();
}
And then you could just use it like this:
private void button1_Click(object sender, EventArgs e)
{
label1.Text = "first";
Delayed(2000, () => label1.Text = "second");
}
Tergiver’s follow-up
Does using Delayed contain a memory leak (reference leak)?
Subscribing to an event always creates a two-way reference.
In this case timer.Tick gets a reference to an anonymous function (lambda). That function lifts a local variable timer, though it's a reference, not a value, and contains a reference to the passed in Action delegate. That delegate is going to contain a reference to label1, an instance member of the Form. So is there a circular reference from the Timer to the Form?
I don't know the answer, I'm finding it a bit difficult to reason about. Because I don't know, I would remove the use of the lambda in Delayed, making it a proper method and having it, in addition to stopping the timer (which is the sender parameter of the method), also remove the event.
Usually lambdas do not cause problems for the garbage collection. In this case, the timer instance only exists locally and the reference in the lambda does not prevent the garbage collection to collect the instances (see also this question).
I actually tested this again using the .NET Memory Profiler. The timer objects were collected just fine, and no leaking happened. The profiler did give me a warning that there are instances that “[…] have been garbage collected without being properly disposed” though. Removing the event handler in itself (by keeping a reference to it) did not fix that though. Changing the captured timer reference to (Timer)s did not change that either.
What did help—obviously—was to call a timer.Dispose() in the event handler after stopping the timer, but I’d argue if that is actually necessary. I don’t think the profiler warning/note is that critical.
If all you're trying to do is change the text when the timer ticks, would you not be better off putting...
label1.Text = "second";
...In the timer tick, either before or after you change the timer to enabled = false;
Like so;
void timer_Tick(object sender, EventArgs e)
{
timer.Stop();
label1.Text = "second";
}
private void button1_Click(object sender, EventArgs e)
{
label1.Text = "first";
timer.Start();
}
private bool Delay(int millisecond)
{
Stopwatch sw = new Stopwatch();
sw.Start();
bool flag = false;
while (!flag)
{
if (sw.ElapsedMilliseconds > millisecond)
{
flag = true;
}
}
sw.Stop();
return true;
}
bool del = Delay(1000);
Related
why I can't close this from it gave me an error message (Cross-thread operation not valid: Control 'Form4' accessed from a thread other than the thread it was created on)
my form code;
System.Timers.Timer t = new System.Timers.Timer();
private void Form4_Load(object sender, EventArgs e)
{ myFunction2();}
private void myFunction2()
{
t.Interval = int.Parse(textBox1.Text);
t.Elapsed += T_Elapsed;
t.Start();
t.AutoReset = false;
}
private void T_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
myFunction();
t.Stop();
t.Enabled = false;
this.Close();
}
private void myFunction()
{
var form6 = new Form6();
//form6.Closed += (s, args) => this.Close();
form6.ShowDialog();}
Edit
I get help from a friend to change this in my code but still, the from4 open and form6 open much time.
private System.Windows.Forms.Timer t = new System.Windows.Forms.Timer();
private void myFunction2()
{
t.Interval = int.Parse(textBox1.Text);
t.Tick += T_Elapsed;
t.Start();
}
private void T_Elapsed(object sender, EventArgs e)
{
myFunction();
this.Invoke((new Action(() =>
this.Close();
})));
}
private void myFunction()
{
Form6 form6 = new Form6();
form6.ShowDialog();}
Winforms has an "owning-thread" model.
What does that mean?
This model prevents you from accessing an UI component from another thread, not the one which created it.
Why?
Because GUI components are not thread-safe. and should not be, since they'll be much slower. So, WinForms throws an exception like that at you when you try to access a GUI component from another thread - not the owned thread.
But why does this happen toyou?
Because System.Timers.Timer executes its callback in its own thread, which isn't the thread that created the GUI (the main thread of the app). So, you can't access from its callback to any GUI component.
What's the solution?
You can access an GUI component from another thread by a tool called a Dispatcher. But if all you want is a simple timer, you have nicer solution.
Simply use System.Windows.Forms.Timer instead of System.Timers.Timer. This timer is specific to WinForms, and handles all the black work with the dispatcher for you. (Note: WPF has System.Windows.Threading.DispatcherTimer for the same purpose).
But, there's one pitfall: this timer has not AutoReset property. So, you should remove the event by hand after one run, like:
private void T_Elapsed(object sender, EventArgs e)
{
myFunction();
t.Stop();
this.Close();
}
Since you're closing the window, this is not really needed, but for safety...
Also, note that you don't need both Stop() and Enabled = false together, they are identical (I personally prefer Stop(), I think it's more readable).
In your example (with AutoReset) you didn't need Stop() at all - AutoReset = false run the callback only one time.
Edit:
Although it isn't needed in your case, I append an explanation about "how to use the dispatcher".
Each WinForms' form has a Dispatcher, and some methods related to it. The most important are Invoke() and BeginInvoke() (two overloaded versions, I'm talking about the first which takes System.Delegate).
These methods enable you two access GUI components from not-owning thread, only from the method passed as parameter (in most cases, you must cast it to System.Delegate first).
The difference is, that Invoke() returns only after the method called, while BeginInvoke() is asynchronous; it returns immediately.
So, you can rewrite you code as follows:
private System.Timers.Timer t = new System.Timers.Timer();
public Form1()
{
InitializeComponent();
t.Elapsed += T_Elapsed;
t.Interval = int.Parse(textBox1.Text);
t.AutoReset = false;
t.Start();
}
private void T_Elapsed(object sender, EventArgs e)
{
this.Invoke((Action)(() => // You can use `BeginInvoke()` as well
{
this.Close();
}));
// Or
// this.Invoke(new Action(() => // You can use `BeginInvoke()` as well
// {
// this.Close();
// }));
}
Note: Never put long-running tasks inside Invoke() or BeginInvoke()! since they're executed in the owning thread - not in the called thread, they'll freeze the GUI - it's much easier to not use threads at all... Put the calculations in the thread, and call these methods only to update the GUI!
Edit 2:
After I saw what you did with my answer, I was shocked... It seems you even didn't read it! You chose both the solutions: the winforms timer (the good), and the dispatcher (the bas, in this case)! simplify you Tick event so:
private void T_Elapsed(object sender, EventArgs e)
{
myFunction();
Close();
}
Also, in your myFunction(), you show your second form in modal form. That say, that the method won't return after the second form is closed. See What's the difference between Show(), ShowDialog() and Application.Run() functions? for more details. I think you want to show your second form modeless.
private System.Windows.Forms.Timer t = new System.Windows.Forms.Timer();
private void T_Elapsed(object sender, EventArgs e)
{
if (true)
{
myFunction();
t.Enabled = false;
t.Stop();
}
}
private void myFunction2()
{
t.Interval = int.Parse(textBox1.Text);
t.Tick += T_Elapsed;
t.Start();
}
private void myFunction()
{
t.Enabled = false;
t.Stop();
this.Hide();
Form6 form6 = new Form6();
form6.ShowDialog();}
I have a function in winform that is executed every x time (eg. every 60 minutes).
And then it does some stuff, then I want it to wait some seconds (using a timer) and then execute do some stuff part2.
private void goToFtp(int time)
{
double interval = time* 60 * 1000;
System.Timers.Timer checkForTime = new System.Timers.Timer(interval);
checkForTime.Elapsed += new ElapsedEventHandler(checkForTime_Elapsed);
checkForTime.Enabled = true;
}
System.Windows.Forms.Timer timerDelayWatcher = new System.Windows.Forms.Timer();
private void checkForTime_Elapsed(object sender, ElapsedEventArgs e)
{
.......Do some stuff part1
timerDelayWatcher.Tick += new EventHandler(timerDelayWatcher_Tick); // Everytime timer ticks, timer_Tick will be called
timerDelayWatcher.Interval = (1000) * (5);
timerDelayWatcher.Enabled = true;
timerDelayWatcher.Start();
}
private void timerDelayWatcher_Tick(object sender, EventArgs e)
{
timerDelayWatcher.Stop();
.......Do some stuff part2
}
The problem is that the timerDelayWatcher_Tick is not fired...any ideias why?
You need use:
Thread.Sleep(5000);
But first you need add
using System.Threading;
or use
System.Threading.Thread.Sleep(5000);
on 5000 are the time in milliseconds
Sample
private void timerDelayWatcher_Tick(object sender, EventArgs e)
{
timerDelayWatcher.Stop();
System.Threading.Thread.Sleep(5000);
.......Do some stuff part2
}
Try calling the start method on the system.timers.timer firstly, and I would recommend sticking to one type of timer, and pattern of use, say use the system.timer.timer and do the work you need on elapsed, then restart with and wait for the next elapsed event.
Either that or I would suggest looking at the task library and async flow in .net 4/4.5 and as #Ferri suggests using a Sleep
Take also care on loosing reference to the class containing the timerDelayWatcher member.
If it happens the timer is disposed so no more events...
I am writing a program to send SMS every 5 minutes. I want to stop this when the system time is 6 PM. How can I do that? This is my current code.
I want to modify this according to my above requirement.
while (true)
{
sms.SendSMS();
Thread.Sleep(30000);
}}).Start();
}
Generally never use Sleep is bad idea , use timer instead:
System.Timers.Timer SendSMS = new System.Timers.Timer();
SendSMS.Interval = 300000; ///300000ms=5min
SendSMS.Elapsed += new System.Timers.ElapsedEventHandler(SendSMS_Elapsed);
SendSMS.Enabled=true;
void SendSMS_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
sms.SendSMS();
}
Add a second timer to check the time and stop when is 6pm:
System.Timers.Timer StopSendSMS = new System.Timers.Timer();
StopSendSMS.Interval = 100;
StopSendSMS.Elapsed += new System.Timers.ElapsedEventHandler( StopSendSMS_Elapsed);
StopSendSMS.Enabled=true;
void StopSendSMS_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
if (int(DateTime.Now.Hour)==18))
{
SendSMS.Enabled=false;
StopSendSMS.Enabled=false; ///no need to check anymore
}
}
You can use the below condition to check system TIME.
`if(DateTime.Now.Hour.ToString("HH") == "18") //Hour is in 24hour format`
I want to raise a function periodically .
When I finish one function cycle to wait some period of time and only them to start the second run.
I thought to make it like :
timer = new System.Timers.Timer();
timer.Interval = 1000;
timer.Enabled = true;
timer.Start();
timer.Elapsed += TimerTick;
private void TimerTick(object sender, EventArgs e)
{
//My functionality
}
But seems that TimerTick is raised every secound and not secound from my last TimerTick run .
How i can solve this one ?
You can use threads:
var thread = new Thread(o => {
while(true)
{
DoTick();
Thread.Sleep(1000);
}
});
You can stop your timer before doing your processing and start it again after it's done:
private void TimerTick(object sender, EventArgs e)
{
timer.Stop();
//My functionality
timer.Start();
}
it's also a good idea to put your functionality in a try-catch and call Start() in the finally section. (if this suits you)
Try the following:
private void TimerTick(object sender, EventArgs e)
{
// get the timer that raised this event (you can have multiple
// timers, or the timer obj is out of scope here, so use this):
Timer timer = (Timer) sender;
// disable (or use timer.Stop())
timer.Enabled = false;
// ...
// your code
// ...
// at end, re-enable
timer.Enabled = true;
}
you will find that the timer will now run 1000ms after your code finished. You can also use timer.Stop() and timer.Start().
you could always do something like this:
while (true)
{
// your functions
Thread.Sleep(1000)
}
you'd have to find a way to stop this through an external mechanism, but it should work.
You're right: the timer will run every second: it won't care what you're doing in the TimerTick.
What you can do is to stop the timer on entering the TimerTick methode.
private void TimerTick(object sender, EventArgs e)
{
timer.Stop();
//My functionality
timer.Start();
}
Try this:
DateTime lastDT = DateTime.MinValue;
private void TimerTick(object sender, EventArgs e)
{
DateTime now = DateTime.Now;
if (now - last).TotalSeconds > what_you_want
{
//My functionality
}
last = now;
}
Using this, your form (main thread) is not locked and you/user can do what you please.
Try
private void TimerTick(object sender, EventArgs e)
{
timer.Stop();
// My Functionality
timer.Stop();
}
However, you may have an extra even fired. As per MSDN Docs:
The signal to raise the Elapsed event is always queued for execution on a ThreadPool thread, so the event-handling method might run on one thread at the same time that a call to the Stop method runs on another thread. This might result in the Elapsed event being raised after the Stop method is called. The code example in the next section shows one way to work around this race condition.
You might want to consider Thread.Sleep() instead
I have a timer that needs to not process its elapsed event handler at the same time. But processing one Elapsed event may interfere with others. I implemented the below solution, but something feels wrong; it seems like either I should be using the timer differently or using another object within the threading space. The timer seemed to fit best because I do need to periodically check for a status, but sometimes checking will take longer than my interval. Is this the best way to approach this?
// member variable
private static readonly object timerLock = new object();
private bool found = false;
// elsewhere
timer.Interval = TimeSpan.FromSeconds(5).TotalMilliseconds;
timer.Elapsed = Timer_OnElapsed;
timer.Start();
public void Timer_OnElapsed(object sender, ElapsedEventArgs e)
{
lock(timerLock)
{
if (!found)
{
found = LookForItWhichMightTakeALongTime();
}
}
}
You could set AutoReset to false, then explicitly reset the timer after you are done handling it. Of course, how you handle it really depends on how you expect the timer to operate. Doing it this way would allow your timer to drift away from the actual specified interval (as would stopping and restarting). Your mechanism would allow each interval to fire and be handled but it may result in a backlog of unhandled events that are handled now where near the expiration of the timer that cause the handler to be invoked.
timer.Interval = TimeSpan.FromSeconds(5).TotalMilliseconds;
timer.Elapsed += Timer_OnElapsed;
timer.AutoReset = false;
timer.Start();
public void Timer_OnElapsed(object sender, ElapsedEventArgs e)
{
if (!found)
{
found = LookForItWhichMightTakeALongTime();
}
timer.Start();
}
I usually stop the timer while processing it, enter a try/finally block, and resume the timer when done.
If LookForItWhichMightTakeALongTime() is going to take a long time, I would suggest not using a System.Windows.Forms.Timer because doing so will lock up your UI thread and the user may kill your application thinking that it has frozen.
What you could use is a BackgroundWorker (along with a Timer if so desired).
public class MyForm : Form
{
private BackgroundWorker backgroundWorker = new BackgroundWorker();
public MyForm()
{
InitializeComponents();
backgroundWorker.DoWork += backgroundWorker_DoWork;
backgroundWorker.RunWorkerCompleted +=
backgroundWorker_RunWorkerCompleted;
backgroundWorker.RunWorkerAsync();
}
private void backgroundWorker_DoWork(object sender, DoWorkEventArgs e)
{
e.Result = LookForItWhichMightTakeALongTime();
}
private void backgroundWorker_RunWorkerCompleted(object sender,
RunWorkerCompletedEventArgs e)
{
found = e.Result as MyClass;
}
}
And you can call RunWorkerAsync() from anywhere you want to, even from a Timer if you want. And just make sure to check if the BackgroundWorker is running already since calling RunWorkerAsync() when it's running will throw an exception.
private void timer_Tick(object sender, EventArgs e)
{
if (!backgroundWorker.IsBusy)
backgroundWorker.RunWorkerAsync();
}
timer.enabled = false
or
timer.stop();
and
timer.enabled = true
or
timer.start();
I use the System.Threading.Timer like so
class Class1
{
static Timer timer = new Timer(DoSomething,null,TimeSpan.FromMinutes(1),TimeSpan.FromMinutes(1));
private static void DoSomething(object state)
{
timer = null; // stop timer
// do some long stuff here
timer = new Timer(DoSomething, null, TimeSpan.FromMinutes(1), TimeSpan.FromMinutes(1));
}
}