亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

C#使用System.Threading.Timer實(shí)現(xiàn)計(jì)時(shí)器的示例詳解

 更新時(shí)間:2024年01月23日 08:47:52   作者:rjcql  
以往一般都是用 System.Timers.Timer 來(lái)做計(jì)時(shí)器,其實(shí) System.Threading.Timer 也可以實(shí)現(xiàn)計(jì)時(shí)器功能,下面就跟隨小編一起來(lái)學(xué)習(xí)一下如何使用System.Threading.Timer實(shí)現(xiàn)計(jì)時(shí)器功能吧

寫(xiě)在前面

以往一般都是用 System.Timers.Timer 來(lái)做計(jì)時(shí)器,而 System.Threading.Timer 也可以實(shí)現(xiàn)計(jì)時(shí)器功能,并且還可以配置首次執(zhí)行間隔,在功能上比System.Timers.Timer更加豐富;根據(jù)這個(gè)特性就可以實(shí)現(xiàn)按指定時(shí)間間隔對(duì)委托進(jìn)行單次調(diào)用。 執(zhí)行的回調(diào)委托也是在 ThreadPool 線(xiàn)程上執(zhí)行,支持多線(xiàn)程運(yùn)行環(huán)境。

代碼實(shí)現(xiàn)

using System;
using System.Threading;
using System.Threading.Tasks;
 
class Program
{
    private static Timer timer;
 
    static void Main(string[] args)
    {
        var dueTime = 1000;  // 首次執(zhí)行延遲時(shí)間
        var interval = 2000; // 后續(xù)執(zhí)行間隔時(shí)間
        var timerState = new TimerState { Counter = 0 };
 
        timer = new Timer(
            callback: new TimerCallback(TimerTask),
            state: timerState,
            dueTime: dueTime,
            period: interval);
 
        Console.WriteLine($"{DateTime.Now:yyyy-MM-dd:HH:mm:ss.fff}: 準(zhǔn)備開(kāi)始執(zhí)行...");
        while (timerState.Counter <= 10)
        {
            Task.Delay(1000).Wait();
        }
 
        timer.Dispose();
        Console.WriteLine($"{DateTime.Now:yyyy-MM-dd:HH:mm:ss.fff}: 完成.");
    }
 
    private static void TimerTask(object timerState)
    {
        Console.WriteLine($"{DateTime.Now:yyyy-MM-dd:HH:mm:ss.fff}: 觸發(fā)了一次新的回調(diào).");
        var state = timerState as TimerState;
        Interlocked.Increment(ref state.Counter);
    }
 
    class TimerState
    {
        // 計(jì)數(shù)器
        public int Counter;
    }
}

調(diào)用示例

到此這篇關(guān)于C#使用System.Threading.Timer實(shí)現(xiàn)計(jì)時(shí)器的示例詳解的文章就介紹到這了,更多相關(guān)C#計(jì)時(shí)器內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評(píng)論