using System;
using System.Threading;
namespace C17_12
{
public class StatusChecker
{
int invokeCount, maxCount;
public StatusChecker(int count)
{
invokeCount = 0;
maxCount = count;
}
//被定時叫用的方法
public void CheckStatus(Object stateInfo)
{
AutoResetEvent autoEvent = (AutoResetEvent)stateInfo;
Console.WriteLine("{0} Checking status {1,2}.", DateTime.Now.ToString("h:mm:ss.fff"), (++invokeCount).ToString());
if (invokeCount == maxCount)
{
invokeCount = 0;
//將事件狀態設置為終止狀態,允許一個或多個等待執行緒繼續
autoEvent.Set();
}
}
}
public class TimerExample
{
public static void Main()
{
AutoResetEvent autoEvent = new AutoResetEvent(false);
StatusChecker statusChecker = new StatusChecker(5);
//建立代理物件TimerCallback,該代理將被定時叫用
TimerCallback timerDelegate = new TimerCallback(statusChecker.CheckStatus);
Console.WriteLine("{0} Creating timer.\n",DateTime.Now.ToString("h:mm:ss.fff"));
//建立一個計時器
Timer stateTimer = new Timer(timerDelegate, autoEvent, 1000, 2000);
autoEvent.WaitOne(5000, false);
//更改stateTimer 的啟動時間和方法叫用之間的間隔
stateTimer.Change(0, 500);
Console.WriteLine("\nChanging period.\n");
autoEvent.WaitOne(5000, false);
//釋放stateTimer使用的所有資源
stateTimer.Dispose();
Console.WriteLine("\nDestroying timer.");
}
}
}
沒有留言:
張貼留言