Thread.Sleep()无需冻结UI [英] Thread.Sleep() without freezing the UI

查看:72
本文介绍了Thread.Sleep()无需冻结UI的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

首先,我是 C#的初学者,我想这样做:

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);

但是此解决方案冻结了UI,我如何使第二个事件在第一个事件之后250ms发生而又没有冻结UI?

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

推荐答案

使用休眠而不冻结UI线程的最简单方法是使方法异步。要使您的方法异步,请添加 async 修饰符。

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()

private async void someMethod()

现在您可以使用等待运算符以执行您的情况下的异步任务。

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

await Task.Delay(milliseconds);

这使它成为异步方法,并将从您的UI线程异步运行。

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

请注意,仅支持此方法在Microsoft .NET Framework 4.5及更高版本中。

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

这篇关于Thread.Sleep()无需冻结UI的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆