I know there is Thread.Sleep
and System.Windows.Forms.Timer
and Monitor.Wait
in C# and Windows Forms. I just can't seem to be able to figure out how to wait for X seconds and then do something else - without locking the thread.
I have a form with a button. On button click a timer shall start and wait for 5 seconds. After these 5 seconds some other control on the form is colored green. When using Thread.Sleep
, the whole application would become unresponsive for 5 seconds - so how do I just "do something after 5 seconds"?
You are looking at it wrong. Click the button, it kicks off a timer with an interval of x seconds. When those are up it's eventhandler executes the task.
So what don't you want to happen.
While the x seconds are elapsing.?
While The task is executing?
If for instance it's you don't want the button to be clicked until delay and task are done. Disable it in the button click handler, and enable it on task completion.
If all you want is a five second delay prior to the task, then you should pass the start delay to the task and let it take care of it.
your application hangs because you are invoking the 5 second sleep/wait on the main UI thread. put the sleep/wait/whatever action in a separate thread (actually System.Windows.Forms.Timer should do that for you) and when it completes invoke the action that turns some control green. remember to check InvokeRequired. here's a short sample (SetText can be called from another thread, if it is the call will instead be invoked on the main UI thread where the textbox is on):
I took the sample from here (well worth a read!).
Have you tried
You can use like this:
reference: https://msdn.microsoft.com/en-us/library/hh194873(v=vs.110).aspx
(transcribed from Ben as comment)
...and disable the timer (IsEnabled=false) before doing your work in oder to suppress a second.
The Tick event may be executed on another thread that cannot modify your gui, you can catch this:
Just for completeness: with async/await, one can delay execute something very easy (one shot, never repeat the invocation):
For more, see "async and await" in MSDN.
I think what you are looking for is
System.Timers
... I don't think you need to set a CWND timer for what you are trying to do: Have a look at http://msdn.microsoft.com/en-us/library/0tcs6ww8(v=VS.90).aspx for an example. It should do the trick.@eFloh in the post marked as answer said:
That is not what the docs say.
You are using a System.Windows.Forms.Timer in your example code.
That is a Forms.Timer.
According to the C# docs the Timer events are raised on the UI thread.
Also see stackoverflow post here