[英]c# run a thread each one minute despite the thread time
我想每隔一分鍾運行一個過程,但是有人告訴我Timer
每隔x minute + the time required for the process to finish
工作。 但是我希望線程每1
分鍾工作一次,即使線程進程可能會持續工作1個小時。
希望您能理解我,因此在最終的圖像中,我可能有10個線程一起工作。
那可能嗎 ?
取決於計時器。 簡單的測試表明System.Threading.Timer
可以按照您想要的方式工作:
var timer = new Timer(s => { "Start".Dump(); Thread.Sleep(10000); "Hi!".Dump(); },
null, 1000, 1000);
Thread.Sleep(20000);
timer.Dump();
即使執行需要十秒鍾,回調也會每秒執行一次。
這基本上是因為該特定計時器的回調僅發布到線程池中,而例如System.Windows.Forms.Timer
實際上已綁定到UI線程。 當然,如果您只是在winforms計時器的回調中啟動一個新線程(或排隊工作,或啟動一個新任務等),它將以類似(盡管不太精確)的方式工作。
使用正確的工具進行工作通常會更容易:)
創建一個Timer並在elapse事件上觸發一個新線程來完成工作,如以下示例所示:
public class Example
{
private static Timer aTimer;
public static void Main()
{
// Create a timer with a two second interval.
aTimer = new Timer(2000);
// Hook up the Elapsed event for the timer.
aTimer.Elapsed += OnTimedEvent;
aTimer.Enabled = true;
Console.WriteLine("Press the Enter key to exit the program... ");
Console.ReadLine();
Console.WriteLine("Terminating the application...");
}
public static void DoWork()
{
var workCounter = 0;
while (workCounter < 100)
{
Console.WriteLine("Alpha.Beta is running in its own thread." + Thread.CurrentThread.ManagedThreadId);
Thread.Sleep(1000);
workCounter++;
}
}
private static void OnTimedEvent(Object source, ElapsedEventArgs e)
{
// Create the thread object, passing in the method
// via a delegate.
var oThread = new Thread(DoWork);
// Start the thread
oThread.Start();
}
}
從.NET 4.0開始,任務優先於線程。 任務管理的開銷很小。
// Create a task spawning a working task every 1000 msec
var t = Task.Run(async delegate
{
while (isRunning)
{
await Task.Delay(1000);
Task.Run(() =>
{
//your work
};
}
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.