Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Thread.Sleep() without freezing the UI

First off, I am a beginner in C# and I would like to make this:

class2.method_79(null, RoomItem_0, num, num2, 0, false, true, true);
System.Threading.Thread.Sleep(250);
class2.method_79(null, RoomItem_0, num, num4, 0, false, true, true);
System.Threading.Thread.Sleep(300);
class2.method_79(null, RoomItem_0, num, num6, 0, false, true, true);

But this solution freezes the UI, how could I make the second event occur 250ms after the first etc without freezing the UI?

like image 336
user3640047 Avatar asked Jun 10 '14 08:06

user3640047


1 Answers

The simplest way to use sleep without freezing the UI thread is to make your method asynchronous. To make your method asynchronous add the async modifier.

private void someMethod()

to

private async void someMethod()

Now you can use the await operator to perform asynchronous tasks, in your case.

await Task.Delay(milliseconds);

This makes it an asynchronous method and will run asynchronously from your UI thread.

Note that this is only supported in the Microsoft .NET framework 4.5 and higher.

.

like image 127
Stella Avatar answered Sep 23 '22 03:09

Stella