探索.NET中的定时器:选择最适合你的应用场景
  KxE3CZnPt4x3 2024年02月29日 82 0

 

概述:.NET提供多种定时器,如
System.Windows.Forms.Timer适用于UI,System.Web.UI.Timer用于Web,System.Diagnostics.Timer用于性能监控,System.Threading.Timer和System.Timers.Timer用于一般定时任务。在.NET 6及以上,还有更直观的System.Threading.PeriodicTimer。选择合适的定时器,提升应用性能和用户体验。

今天看到一网友聊.net中的定时器,我也把我知道和大家分享一下。 在.NET中,有多种定时器的实现,每一种都有其特定的应用场景和特点。下面将分别介绍这几种定时器,并提供相应的实例源代码。

1. System.Windows.Forms.Timer

应用场景: 适用于Windows Forms应用程序中需要与UI线程交互的场景。

特点: 在UI线程中工作,可以直接访问和操作UI控件。

实例:

using System;
using System.Windows.Forms;

public class MainForm : Form
{
    private Timer timer;

    public MainForm()
    {
        // 创建定时器,每秒触发一次
        timer = new Timer();
        timer.Interval = 1000;
        timer.Tick += TimerTick;

        // 启动定时器
        timer.Start();
    }

    private void TimerTick(object sender, EventArgs e)
    {
        // 在UI线程中更新UI
        label1.Text = "定时器触发时间:" + DateTime.Now;
    }

    static void Main()
    {
        Application.Run(new MainForm());
    }
}

2. System.Windows.Threading.DispatcherTimer

应用场景: 适用于WPF应用程序中需要与UI线程交互的场景。

特点: 基于WPF的 Dispatcher,可直接访问和操作UI控件。

实例:

using System;
using System.Windows;
using System.Windows.Threading;

public partial class MainWindow : Window
{
    private DispatcherTimer timer;

    public MainWindow()
    {
        // 创建定时器,每秒触发一次
        timer = new DispatcherTimer();
        timer.Interval = TimeSpan.FromSeconds(1);
        timer.Tick += TimerTick;

        // 启动定时器
        timer.Start();
    }

    private void TimerTick(object sender, EventArgs e)
    {
        // 在UI线程中更新UI
        label1.Content = "定时器触发时间:" + DateTime.Now.ToString("HH:mm:ss");
    }

    static void Main()
    {
        Application app = new Application();
        app.Run(new MainWindow());
    }
}

3. System.Web.UI.Timer

应用场景: 适用于ASP.NET Web应用程序中,用于在Web页面上执行定时操作。

特点: 在Web页面的服务器端运行,适用于Web Forms。

实例:

ASP.NET Web Forms中在aspx页面的代码:

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
        <asp:ScriptManager runat="server" />
        <asp:UpdatePanel runat="server">
            <ContentTemplate>
                <asp:Label ID="Label1" runat="server" Text="定时器触发时间:" />
                <asp:Timer ID="Timer1" runat="server" Interval="1000" OnTick="TimerTick"></asp:Timer>
            </ContentTemplate>
        </asp:UpdatePanel>
    </form>
</body>
</html>

对应的代码文件 Default.aspx.cs

using System;

public partial class _Default : System.Web.UI.Page
{
    protected void TimerTick(object sender, EventArgs e)
    {
        // 在服务器端更新UI
        Label1.Text = "定时器触发时间:" + DateTime.Now.ToString("HH:mm:ss");
    }
}

4. System.Diagnostics.Timer

应用场景: 适用于性能计数器的定时器,用于性能监控和测量。

特点: 基于性能计数器的定时器。

实例:

using System;
using System.Diagnostics;

class Program
{
    static void Main()
    {
        // 创建定时器,每秒触发一次
        Timer timer = new Timer(1000);
        
        // 定时器触发事件
        timer.Elapsed += TimerElapsed;

        // 启动定时器
        timer.Start();

        // 阻止程序退出
        Console.ReadLine();
    }

    static void TimerElapsed(object sender, ElapsedEventArgs e)
    {
        Console.WriteLine("定时器触发时间:" + e.SignalTime);
    }
}

5. System.Timers.Timer

应用场景: 适用于需要在一定时间间隔内重复执行任务的场景,如定时数据采集、日志记录等。

特点: 基于事件触发机制,可在多线程环境中使用,但注意处理线程同步。

实例:

using System;
using System.Timers;

class Program
{
    static void Main()
    {
        // 创建定时器,每秒触发一次
        Timer timer = new Timer(1000);

        // 定时器触发事件
        timer.Elapsed += TimerElapsed;

        // 启动定时器
        timer.Start();

        // 阻止程序退出
        Console.ReadLine();
    }

    static void TimerElapsed(object sender, ElapsedEventArgs e)
    {
        Console.WriteLine("定时器触发时间:" + e.SignalTime);
    }
}

6. System.Threading.Timer

应用场景: 适用于需要在一定时间间隔内执行任务,但不需要与UI线程交互的场景,如后台任务的调度。

特点: 基于线程池,不依赖于UI线程,需要注意线程同步和异常处理。

实例:

using System;
using System.Threading;

class Program
{
    static void Main()
    {
        // 创建定时器,每秒触发一次
        Timer timer = new Timer(TimerCallback, null, 0, 1000);

        // 阻止程序退出
        Console.ReadLine();
    }

    static void TimerCallback(object state)
    {
        Console.WriteLine("定时器触发时间:" + DateTime.Now);
    }
}

7. System.Threading.PeriodicTimer (需要.NET 6及以上版本)

应用场景: 适用于需要定期执行任务的场景,替代 System.Threading.Timer

特点: .NET 6及以上版本引入的新型定时器,提供更直观的API和更稳定的性能。

实例:

using System;
using System.Threading;

class Program
{
    static void Main()
    {
        // 创建定时器,每秒触发一次
        using (PeriodicTimer timer = new PeriodicTimer(TimeSpan.FromSeconds(1)))
        {
            // 定时器触发事件
            timer.Elapsed += TimerElapsed;

            // 启动定时器
            timer.Start();

            // 阻止程序退出
            Console.ReadLine();
        }
    }

    static void TimerElapsed(object sender, EventArgs e)
    {
        Console.WriteLine("定时器触发时间:" + DateTime.Now);
    }
}

这些定时器各自适用于不同的场景,选择合适的定时器取决于你的具体需求和应用程序类型。

在使用定时器时,请注意处理好线程同步、资源释放等问题,以确保应用程序的稳定性和性能。

 

【版权声明】本文内容来自摩杜云社区用户原创、第三方投稿、转载,内容版权归原作者所有。本网站的目的在于传递更多信息,不拥有版权,亦不承担相应法律责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@moduyun.com

  1. 分享:
最后一次编辑于 2024年02月29日 0

暂无评论

推荐阅读
  NPQODODLqddb   2024年05月17日   71   0   0 .NET
  mVIyUuLhKsxa   2024年05月17日   53   0   0 .NET
  XkHDHG7Y62UM   2024年05月17日   45   0   0 .NET
  f18CFixvrKz8   2024年05月18日   88   0   0 .NET
  rBgzkhl6abbw   2024年05月18日   78   0   0 .NET
  MYrYhn3ObP4r   2024年05月17日   41   0   0 .NET
  S34pIcuyyIVd   2024年05月17日   60   0   0 .NET
  gKJ2xtp6I8Y7   2024年05月17日   55   0   0 .NET
  MYrYhn3ObP4r   2024年05月17日   40   0   0 .NET
KxE3CZnPt4x3