[英]Best way to make a polling thread
在我的應用程序中,我需要一個每N秒與服務器聯系一次的后台線程。
我以這種方式做到了:
Task.Factory.StartNew (() => {
while(true)
{
Thread.Sleep (10000);
...do my stuff...
}
});
此解決方案效果很好,但我需要知道是否有更好的解決方案。 (例如:Task.Delay(10000)是更好的解決方案嗎?)
非常感謝!
如果需要使用UI,則可以使用DaveDev的示例,否則下面的示例也可以使用。 如果要在此示例中使用UI,則必須使用控件的Invoke
或BeginInvoke
方法。
using System;
using System.Threading;
class TimerExample
{
static void Main()
{
// Create a timer that signals the delegate to invoke
// CheckStatus after one second, and every 1/4 second
// thereafter.
Timer stateTimer = new Timer(CheckStatus);
// Change the period to every 1/2 second.
stateTimer.Change(0, 500);
}
public static void CheckStatus(Object stateInfo) {
...
}
}
我認為了解這種情況下為什么不使用Thread.Sleep
至關重要。 如果使用sleep,它將鎖定線程。 如果使用計時器,則該線程可同時用於執行其他任務。
_timer = new DispatcherTimer();
_timer.Tick += timer_Tick;
_timer.Interval = new TimeSpan(0, 0, 0, 1);
_timer.Start();
private void timer_Tick(object sender, EventArgs e)
{
BackgroundWorker backgroundWorker = new BackgroundWorker();
backgroundWorker.DoWork += (s, a) =>
{
//do your stuff
};
backgroundWorker.RunWorkerAsync();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.