給定以下代碼,計時器將每隔一秒觸發PrintTimer函數,直到用戶按下一個鍵。C# - Timer的實例何時會被殺死?
問題1>定時器何時停止? 定時器默認爲後臺線程,所以它會在前臺線程終止後被終止。
問題2>如何以編程方式停止調用線程中的計時器?
class Program
{
// continue to call this function until the user presses a
// key to terminate the application
static void PrintTime(object state)
{
Console.WriteLine("Time is: {0}",
DateTime.Now.ToLongTimeString());
}
static void Main(string[] args)
{
TimerCallback timeCB = new TimerCallback(PrintTime);
System.Threading.Timer t = new Timer(
timeCB,
null,
0,
1000);
Console.WriteLine("Hit key to terminate...");
Console.ReadLine();
}
}
我有這麼多的選擇(即處置,關閉,停止),何時使用? -thx – q0987 2011-05-28 00:03:31