I would like to wait some seconds between two instruction, but WITHOUT blocking the execution.
For example, Thread.Sleep(2000)
it is not good, because it blocks execution.
The idea is that I call a method and then I wait X seconds (20 for example) listening for an event coming. At the end of the 20 seconds I should do some operation depending on what happened in the 20 seconds.
This is a good case for using another thread:
The above code expects .NET 4.0 or above, otherwise try:
I think what you are after is Task.Delay. This doesn't block the thread like Sleep does and it means you can do this using a single thread using the async programming model.
i really disadvise you against using
Thread.Sleep(2000)
, because of a several reasons (a few are described here), but most of all because its not useful when it comes to debugging/testing.I recommend to use a C# Timer instead of
Thread.Sleep()
. Timers let you perform methods frequently (if necessary) AND are much easiert to use in testing! There's a very nice example of how to use a timer right behind the hyperlink - just put your logic "what happens after 2 seconds" right into theTimer.Elapsed += new ElapsedEventHandler(OnTimedEvent);
method.If you do not want to block things and also not want to use multi threading, here is the solution for you: https://msdn.microsoft.com/en-us/library/system.timers.timer(v=vs.110).aspx
The UI Thread is not blocked and the timer waits for 2 seconds before doing something.
Here is the code coming from the link above:
Look into
System.Threading.Timer
class. I think this is what you're looking for.The code example on MSDN seems to show this class doing very similar to what you're trying to do (check status after certain time).
I use: