我會假設你有一個很好的理由使用獨立管理的線程做的工作(而不是僅僅做在計時器的事件)。如果是這樣,你想用WaitHandle.WaitAny()
並檢查返回值來確定的WaitHandle導致線程進行:
public class ExampleService
{
private static readonly AutoResetEvent TimerLatch = new AutoResetEvent(false);
private static readonly AutoResetEvent ShutdownLatch = new AutoResetEvent(false);
private static readonly Timer MyTimer = new Timer(TimerTick);
public void Start()
{
var t = new Thread(DoLoop);
t.Start();
MyTimer.Change(0, 500);
}
public void Stop()
{
ShutdownLatch.Set();
}
private static void TimerTick(object state)
{
TimerLatch.Set();
}
private static void DoLoop()
{
if (WaitHandle.WaitAny(new[] { TimerLatch, ShutdownLatch }) == 0)
{
// The timer ticked, do something timer related
}
else
{
// We are shutting down, do whatever cleanup you need
}
}
}
,你不只是使用'Timer'做的工作(而不是使用定時器鎖存工作線程)有什麼特別的原因嗎? – 2012-03-31 17:54:35
一個線程太貴,系統對象沒有任何用處,只能等待幾個小時。您可以從Timer類免費獲得線程。 – 2012-03-31 18:13:22
這是一個現有的服務,目前有一個線程用於不同類型的處理。它目前使用Thread.Abort()和Sleep。我將研究使用Timer和它所產生的線程。 – codezoo 2012-03-31 19:27:02