欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

.NET 6新特性試用Timer類之PeriodicTimer?

 更新時間:2022年03月14日 14:17:35   作者:My IO  
這篇文章主要介紹了.NET 6新特性試用Timer類之PeriodicTimer,PeriodicTimer與其他Timer需要創(chuàng)建事件回調(diào)不同,下,下面文章詳細(xì)介紹PeriodicTimer的使用方式,需要的朋友可以參考一下

前言:

在.NET中,已經(jīng)存在了5個Timer類:

System.Threading.Timer
System.Timers.Timer
System.Web.UI.Timer
System.Windows.Forms.Timer
System.Windows.Threading.DispatcherTimer

不管以前這樣設(shè)計的原因,現(xiàn)在.NET 6又為我們增加了一個新Timer,??PeriodicTimer??。

這又是為什么呢?

一、Demo

與其他Timer需要創(chuàng)建事件回調(diào)不同:

Timer timer = new Timer(delegate
{
? ? Thread.Sleep(3000);
? ? Console.WriteLine($"Timer Thread: {Thread.CurrentThread.ManagedThreadId}");
? ? Console.WriteLine($"{DateTime.Now.Second} Timer tick");
},null,0,1000
);

PeriodicTimer的使用方式如下:

//間隔時間1秒
using (var timer = new PeriodicTimer(TimeSpan.FromSeconds(1)))
{
? ? //在到達(dá)指定周期后執(zhí)行方法
? ? while (await timer.WaitForNextTickAsync())
? ? {
? ? ? ? await Task.Delay(3000);
?
? ? ? ? Console.WriteLine($"Timer Thread: {Thread.CurrentThread.ManagedThreadId}");
? ? ? ? Console.WriteLine($"{DateTime.Now.Second} PeriodicTimer tick");
? ? }
}

?從??await??關(guān)鍵字可以看出,PeriodicTimer用于異步執(zhí)行;并且一次只有一個線程可以執(zhí)行。

另外,你可以控制?停止PeriodicTimer計時?。示例代碼如下:

//創(chuàng)建CancellationTokenSource,指定在3秒后將被取消
var cts = new CancellationTokenSource(TimeSpan.FromSeconds(3));

using (var timer = new PeriodicTimer(TimeSpan.FromSeconds(1)))
{
? ? while (await timer.WaitForNextTickAsync(cts.Token))
? ? {
? ? ? ? Console.WriteLine($"{DateTime.Now.Second} PeriodicTimer tick");
? ? }
}

需要注意的是,這會引發(fā)??OperationCancelled??異常,你需要捕獲該異常,然后根據(jù)需要進(jìn)行處理:

當(dāng)然,你也可以通過主動取消CancellationTokenSource,來停止PeriodicTimer計時,

示例代碼如下:

var cts = new CancellationTokenSource();

using (var timer = new PeriodicTimer(TimeSpan.FromSeconds(1)))
{
? ? int count = 0;
? ? while (await timer.WaitForNextTickAsync(cts.Token))
? ? {
? ? ? ? if (++count == 3)
? ? ? ? {
? ? ? ? ? ? //執(zhí)行3次后取消
? ? ? ? ? ? cts.Cancel();
? ? ? ? }
? ? ? ? Console.WriteLine($"{DateTime.Now.Second} PeriodicTimer tick");
? ? }
}

這次換成了??TaskCancelled??異常:

如果,你不想拋出異常,則可以用PeriodicTimer.Dispose方法來停止計時,

示例代碼如下:

using (var timer = new PeriodicTimer(TimeSpan.FromSeconds(1)))
{
? ? int count = 0;
? ? while (await timer.WaitForNextTickAsync())
? ? {
? ? ? ? if (++count == 3)
? ? ? ? {
? ? ? ? ? ? //執(zhí)行3次后取消
? ? ? ? ? ? timer.Dispose();
? ? ? ? }
? ? ? ? Console.WriteLine($"{DateTime.Now.Second} PeriodicTimer tick");
? ? }
}

結(jié)論:

通過上面的代碼,可以了解到,設(shè)計PeriodicTimer的原因,可以歸結(jié)為:

  • 用于異步上下文
  • 一次僅由一個消費者使用?

 到此這篇關(guān)于.NET 6新特性試用Timer類之PeriodicTimer 的文章就介紹到這了,更多相關(guān)Timer類之PeriodicTimer 內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評論