Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Asynchronous Thread.Sleep()

I want to put a delay between 2 operations without keeping busy the thread

 workA();  Thread.Sleep(1000);  workB(); 

The thread must exit after workA and execute workB (maybe in a new thread) after some delay.

I wonder if it's possible some equevalent of this pseudocode

workA(); Thread.BeginSleep(1000, workB); // callback 

edit My program is in .NET 2.0

edit 2 : System.Timers.Timer.Elapsed event will raise the event after 1000 ms. I dont know if the timer thread will be busy for 1000 ms. (so I dont gain thread economy)

like image 728
albert Avatar asked Apr 10 '13 11:04

albert


People also ask

What's thread sleep () in threading?

Thread. sleep() method can be used to pause the execution of current thread for specified time in milliseconds. The argument value for milliseconds can't be negative, else it throws IllegalArgumentException .

What is the difference between task delay and thread sleep?

Use Thread. Sleep when you want to block the current thread. Use Task. Delay when you want a logical delay without blocking the current thread.

Is it safe to use thread sleep in Java?

Thread. sleep is bad! It blocks the current thread and renders it unusable for further work.

Does thread sleep block thread?

Sleep method. Calling the Thread. Sleep method causes the current thread to immediately block for the number of milliseconds or the time interval you pass to the method, and yields the remainder of its time slice to another thread. Once that interval elapses, the sleeping thread resumes execution.


1 Answers

Do you mean:

Task.Delay(1000).ContinueWith(t => workB()); 

Alternatively, create a Timer manually.

Note this looks prettier in async code:

async Task Foo() {     workA();     await Task.Delay(1000);     workB(); } 

edit: with your .NET 2.0 update, you would have to setup your own Timer with callback. There is a nuget package System.Threading.Tasks that brings the Task API down to .NET 3.5, but a: it doesn't go to 2.0, and b: I don't think it includes Task.Delay.

like image 149
Marc Gravell Avatar answered Oct 04 '22 16:10

Marc Gravell