[英]Wait for a while without blocking main thread
我希望我的方法等待大約 500 毫秒,然后檢查某些標志是否已更改。 如何在不阻塞應用程序的其余部分的情況下完成此操作?
Thread.Sleep(500)
將強制當前線程等待 500 毫秒。 它可以工作,但如果您的整個應用程序都在一個線程上運行,這不是您想要的。
在這種情況下,您將需要使用Timer
,如下所示:
using System.Timers;
void Main()
{
Timer t = new Timer();
t.Interval = 500; // In milliseconds
t.AutoReset = false; // Stops it from repeating
t.Elapsed += new ElapsedEventHandler(TimerElapsed);
t.Start();
}
void TimerElapsed(object sender, ElapsedEventArgs e)
{
Console.WriteLine("Hello, world!");
}
如果您希望計時器自動重復,您可以將AutoReset
設置為 true(或根本不設置)。
您可以使用await Task.Delay(500);
不會像Sleep
那樣阻塞線程,並且代碼比 Timer 少很多。
如果有問題的方法與應用程序的其余部分在不同的線程上執行,請執行以下操作:
Thread.Sleep(500);
System.Threading.Thread.Sleep(500);
更新
這不會阻塞應用程序的其余部分,只會阻塞正在運行您的方法的線程。
使用計時器應該可以解決問題
如果您需要使用線程,那么這里是一個示例
void Main()
{
System.Threading.Thread check= new System.Threading.Thread(CheckMethod);
check.Start();
}
private void CheckMethod()
{
//Code
Thread.Sleep(500);
}
異步任務:
var task = new Task (() => function_test()); task.Start();
public void function_test() { `Wait for 5000 miliseconds` Task.Delay(5000);` }
我最近一直在努力解決同樣的問題,我需要在不阻塞 UI 的情況下按計划運行操作。
這是我的解決方案:
private void Button_Click(object sender, RoutedEventArgs e)
{
RunOnSchedule(interval, cancellationToken);
}
private void RunOnSchedule(int interval, CancellationToken cancellationToken)
{
// Start the task you want to run on schedule
TaskToRunOnSchedule(args);
Task.Run(async () =>
{
// This loop checks if the task was requested to be cancelled every 1000 ms
for (int x = 0; x < interval; x+=1000)
{
if (cancellationToken.IsCancellationRequested)
{
break;
}
await Task.Delay(1000);
}
}).GetAwaiter().OnCompleted(() =>
{
// Once the task for delaying is completed, check once more if cancellation is requested, as you will reach this point regardless of if it was cancelled or not.
if (!cancellationToken.IsCancellationRequested)
{
// Run this method again
RunOnSchedule(interval, cancellationToken);
}
});
}
在 WinForms 應用程序中,當我想在主線程上等待而不阻塞應用程序時,我通常使用
private void Wait (double milliseconds)
{
DateTime next = System.DateTime.Now.AddMilliseconds(milliseconds);
while (next > System.DateTime.Now)
Application.DoEvents();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.