簡體   English   中英

Thread.Sleep() 不凍結 UI

[英]Thread.Sleep() without freezing the UI

首先,我是C#的初學者,我想做這個:

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,我怎樣才能讓第二個事件在第一個事件等 250 毫秒后發生而不凍結 UI?

在不凍結 UI 線程的情況下使用睡眠的最簡單方法是使您的方法異步。 要使您的方法異步,請添加async修飾符。

private void someMethod()

private async void someMethod()

現在,根據您的情況,您可以使用await運算符執行異步任務。

await Task.Delay(milliseconds);

這使它成為一種異步方法,並將從您的 UI 線程異步運行。

請注意,這僅在 Microsoft .NET Framework 4.5 及更高版本中受支持。

.

您可以使用Dispatcher Timer來計時方法的執行。

當您調用.Sleep(); .

這就是它凍結用戶界面的原因。 如果您需要在不凍結 UI 的情況下執行此操作,則需要在單獨的線程中運行代碼。

在單獨的線程上運行耗時的任務。 避免在 UI 線程上執行耗時的任務和Thread.Sleep()

試試這個代碼

public static void wait(int milliseconds)
        {
            System.Windows.Forms.Timer timer1 = new System.Windows.Forms.Timer();
            if (milliseconds == 0 || milliseconds < 0) return;
            timer1.Interval = milliseconds;
            timer1.Enabled = true;
            timer1.Start();
            timer1.Tick += (s, e) =>
            {
                timer1.Enabled = false;
                timer1.Stop();
            };
            while (timer1.Enabled)
            {
                Application.DoEvents();
            }
        }

做一個async函數。 將該函數放入Task.Factory.StartNew中,然后使用Thread.Sleep()

例子:

private void btnExample_Click(object sender, EventArgs e)
{
    System.Threading.Tasks.Task.Factory.StartNew(() =>
    {
        System.Threading.Thread.Sleep(2000);
        MessageBox.Show("First message after one second without freezing");
        System.Threading.Thread.Sleep(2000);
        MessageBox.Show("Second message after one second without freezing");
        System.Threading.Thread.Sleep(2000);
        MessageBox.Show("Third message after one second without freezing");
    });
}

測試視頻

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM