Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
850 views
in Technique[技术] by (71.8m points)

c# - 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?

question from:https://stackoverflow.com/questions/65869330/how-do-you-wait-a-certain-time-before-showing-a-messagebox-on-windows-forms-appl

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.

.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.9k users

...