C# .NET 6 System.Threading.PeriodicTimer 使用示範

在 .NET 6 中有了新的 Timer,使用 while 等待計時器指定的時間後持續重複,主要用在單一執行緒上。

基本使用範例:
    
int i = 0;

System.Threading.PeriodicTimer timer = new System.Threading.PeriodicTimer(TimeSpan.FromMilliseconds(1000));

while (await timer.WaitForNextTickAsync())
{
    Console.WriteLine(DateTime.Now.ToString("O"));

    i++;
    if (i == 3) timer.Dispose(); // 停止 timer 
}
    

在上面的範例中會執行三次後停止,才會繼續執行後面的程式碼,假設想要讓計時器非同步執行的話可以使用 Task
    
int i = 0;

PeriodicTimer timer = new PeriodicTimer(TimeSpan.FromMilliseconds(1000));

async Task Tick()
{
    while (await timer.WaitForNextTickAsync())
    {
        Console.WriteLine(DateTime.Now.ToString("O"));

        i++;
        if (i == 3) timer.Dispose(); // 停止 timer 
    }
}

Tick();

Console.WriteLine("會先輸出這行才輸出時間");
    

不過如果是用這樣的方式使用,就不需要 System.Threading.PeriodicTimer 上場了,使用其他的 Timer 更方便。

留言