日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學(xué)無(wú)先后,達(dá)者為師

網(wǎng)站首頁(yè) 編程語(yǔ)言 正文

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

作者:My?IO ? 更新時(shí)間: 2022-04-20 編程語(yǔ)言

前言:

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

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

不管以前這樣設(shè)計(jì)的原因,現(xiàn)在.NET 6又為我們?cè)黾恿艘粋€(gè)新Timer,??PeriodicTimer??。

這又是為什么呢?

一、Demo

與其他Timer需要?jiǎng)?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的使用方式如下:

//間隔時(shí)間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í)行;并且一次只有一個(gè)線程可以執(zhí)行。

另外,你可以控制?停止PeriodicTimer計(jì)時(shí)?。示例代碼如下:

//創(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");
? ? }
}

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

當(dāng)然,你也可以通過(guò)主動(dòng)取消CancellationTokenSource,來(lái)停止PeriodicTimer計(jì)時(shí),

示例代碼如下:

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方法來(lái)停止計(jì)時(shí),

示例代碼如下:

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é)論:

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

  • 用于異步上下文
  • 一次僅由一個(gè)消費(fèi)者使用?

原文鏈接:https://blog.51cto.com/MyIO/5026597

欄目分類
最近更新