假設我們有一個下面的程序,在其Start方法中,它將一些長時間運行的任務委託給另一個線程。當Stop方法被調用時,我需要確保工作線程完成執行當前任務並且不會將其留在中間。如果它已完成任務並處於睡眠狀態,則可以立即停止。等待主線程停止,直到任務被異步線程處理
請指導我該怎麼做。
static int itemsProcessed = 0;
static Thread worker;
static void Start()
{
var ts = new ThreadStart(Run);
worker = new Thread(ts);
worker.Start();
}
static void Stop()
{
//wait until the 'worker' completes processing the current item.
Console.WriteLine("{0} Items Processed", itemsProcessed);
}
static void Run(object state)
{
while (true)
{
ALongRunningTask();
itemsProcessed++;
Thread.Sleep(1000);
}
}
這需要處理爲易失性,否則其他線程可能永遠不會注意到值被更改。您也可以使用worker.Join方法代替睡眠循環。 – 2010-12-03 05:06:38