欢迎大家来到IT世界,在知识的湖畔探索吧!
在.NET开发中,定时器是一种常见的功能,用于在特定时间间隔执行任务。.NET框架提供了多种定时器,每种都有其特定的用途和特点。本文将介绍.NET中的几种定时器,并分享示例代码,帮助你理解它们的用法和适用场景。
```csharppublic partial class TimerForm : Form{private System.Windows.Forms.Timer digitalClock;public TimerForm(){InitializeComponent();digitalClock = new System.Windows.Forms.Timer();digitalClock.Tick += new EventHandler(HandleTime);digitalClock.Interval = 1000; // 设置时间间隔为1秒digitalClock.Start();}private void HandleTime(object myObject, EventArgs myEventArgs){labelClock.Text = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");}private void TimerForm_FormClosed(object sender, FormClosedEventArgs e){digitalClock.Stop();}}```
欢迎大家来到IT世界,在知识的湖畔探索吧!
欢迎大家来到IT世界,在知识的湖畔探索吧!```csharpprivate void Dt_Tick(object sender, EventArgs e){Dispatcher.BeginInvoke((Action)delegate(){text1.Text = DateTime.Now.ToString();});Console.WriteLine(DateTime.Now.ToString());}private void Button_Click(object sender, RoutedEventArgs e){Task.Run(() =>{DispatcherTimer dt = new DispatcherTimer();dt.Tick += Dt_Tick;dt.Interval = TimeSpan.FromSeconds(1);dt.Start();Dispatcher.Run();});}```
```csharpvar timer = new System.Threading.Timer(CheckStatus, , 0, 1000);private void CheckStatus(object state){Console.WriteLine($"{DateTime.Now} - Checking status.");}```
欢迎大家来到IT世界,在知识的湖畔探索吧!```csharpSystem.Timers.Timer timer = new System.Timers.Timer();timer.Elapsed += OnElapsed;timer.AutoReset = true;timer.Interval = 1000;timer.Enabled = true;private void OnElapsed(object sender, System.Timers.ElapsedEventArgs args){Console.WriteLine($"{DateTime.Now} - Elapsed.");}```
```csharpvar timer = new PeriodicTimer(TimeSpan.FromSeconds(1));try{while (await timer.WaitForNextTickAsync()){Console.WriteLine($"{DateTime.Now} - Tick.");}}catch (OperationCanceledException){Console.WriteLine("Operation cancelled");}```
免责声明:本站所有文章内容,图片,视频等均是来源于用户投稿和互联网及文摘转载整编而成,不代表本站观点,不承担相关法律责任。其著作权各归其原作者或其出版社所有。如发现本站有涉嫌抄袭侵权/违法违规的内容,侵犯到您的权益,请在线联系站长,一经查实,本站将立刻删除。 本文来自网络,若有侵权,请联系删除,如若转载,请注明出处:https://itzsg.com/93193.html