簡體   English   中英

System.Windows.Forms.Timer的同步行為

[英]synchronous behavior of System.Windows.Forms.Timer

根據MSDN博客http://msdn.microsoft.com/en-us/magazine/cc164015.aspx

此計時器類引發的計時器事件與Windows Forms應用程序中的其余代碼是同步的。駐留在計時器事件處理程序中(對於此類計時器類)的任何代碼都是使用應用程序的UI線程執行的

現在看下面的代碼

 private void Form1_Load(object sender, EventArgs e)
     {
         timer1.Tick += timer1_Tick;
         timer1.Start();
         Thread.Sleep(10000);
      }

 void timer1_Tick(object sender, EventArgs e)
     {
         textBox1.Text = (Convert.ToInt32(textBox1.Text) + 1).ToString();
     }

我的問題是

為什么在主UI線程處於休眠狀態時更新textBox1值。

不是。 Tick事件仍將在適當的時間引發,並且事件處理程序將排隊。 Sleep調用返回並且您的load事件處理程序完成時,將執行Tick事件處理程序並更新TextBox

請注意,如果在UI線程繁忙/睡眠時多次Tick事件,則事件處理程序在空閑后將多次執行。

要向自己證明,請嘗試以下代碼:

private readonly Stopwatch watch = new Stopwatch();

private void Form1_Load(object sender, EventArgs e)
{
    this.timer1.Interval = 15000;
    this.timer1.Tick += timer1_Tick;
    this.timer1.Start();
    this.watch.Start();
    Thread.Sleep(20000);
}

private void timer1_Tick(object sender, EventArgs e)
{
    this.timer1.Stop();
    this.label1.Text = this.watch.Elapsed.ToString();
}

如果在UI線程處於休眠狀態時Tick事件處理程序正在更新Label ,則您希望LabelText表示大約15秒,因為那是TimerInterval 相反,您將看到它代表大約20秒,這是UI線程休眠的時間。 這表明直到Sleep調用完成才執行Tick事件處理程序。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM