Timer 使用的注意事項 (.NET 為例)

來源:互聯網
上載者:User

timer ,顧名思義:定時器;在程式中,需要定期去做某件事時,timer通常都是我們的首選,因為timer確實簡單易用 。

通常,我們使用timer時,只做兩件事:

  1. 給 timer 指定一個 interval值, 該值是以 毫秒為單位的(但是準確度沒有那麼高 )。

      我們這裡,比如賦值 2000 (2秒)

  2.  在 timer 的 tick 事件裡,加入要做的事

private void timer1_Tick( object sender, EventArgs e ){    // dosomething();}
一般情況下, 上面的就OK啦 
就上面的例子, 假定 interval 設定為 2000(2秒)
而 dosomething() 耗時為 3 秒或更多,那會發生什麼事情呢?

結果是 dosomething 執行結束後,並沒有等待2秒,而是直接又執行了一次,重複下去,違背了我們的初衷。

下面的例子,可以在很大程度上解決上面的問題:

private void timer1_Tick( object sender, EventArgs e ){    timer1.Stop(); //先停止timer    try    {        //dosomething();    }    finally    {        timer1.Start();  //要做事情結束後,再開始計時    }}    

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.