Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Thread.Sleep replacement in .NET for Windows Store

Thread.Sleep doesn't seem to be supported in .NET for Windows Store apps.

For example, this

System.Threading.Thread.Sleep(1000); 

will compile when targeting any .NET Framework (2.0, 3.5, 4.0, 4.5), but not when targeting .NET for Windows Store apps (or in a portable class library which targets both 4.5 and store).

System.Threading.Thread is still there, it just doesn't have the Sleep method.

I need to delay something for a few seconds in my app, is there a suitable replacement?

EDIT why the delay is needed: My app is a game and the delay is to make it look like the computer opponent is "thinking" about his next move. The method is already called asynchronously (main thread isn't blocked), I just want to slow the response time down.

like image 828
Max Avatar asked Sep 28 '12 13:09

Max


People also ask

What's thread sleep () in threading in C#?

In C#, a Sleep() method temporarily suspends the current execution of the thread for specified milliseconds, so that other threads can get the chance to start the execution, or may get the CPU for execution.

Is Task delay better than 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.

How do you call a sleep method in C#?

In c#, the sleep method is useful to suspend or pause the current thread execution for a specified time. We can suspend the thread execution either by passing the time in milliseconds or with TimeSpan property like as shown below. TimeSpan ts = new TimeSpan(0,0,1);

Does thread sleep create a new thread?

Java Thread Sleep important points For a quiet system, the actual time for sleep is near to the specified sleep time but for a busy system it will be little bit more. Thread sleep doesn't lose any monitors or locks current thread has acquired.


1 Answers

Windows Store apps embrace asynchrony - and an "asynchronous pause" is provided by Task.Delay. So within an asynchronous method, you'd write:

await Task.Delay(TimeSpan.FromSeconds(30)); 

... or whatever delay you want. The asynchronous method will continue 30 seconds later, but the thread will not be blocked, just as for all await expressions.

like image 91
Jon Skeet Avatar answered Oct 06 '22 00:10

Jon Skeet