C#教程

关注公众号 jb51net

关闭
首页 > 软件编程 > C#教程 > C# Stopwatch timer

C# 中Stopwatch和timer的实现示例

作者:就是有点傻

本文主要介绍了C# 中Stopwatch和timer的实现示例,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧

在C#中,StopwatchTimer(通常指的是 System.Timers.TimerSystem.Windows.Forms.Timer)是两个不同的类,它们用于不同的目的:

Stopwatch 类

Stopwatch 类位于 System.Diagnostics 命名空间,主要用于精确测量时间间隔。它非常适合用于性能分析、测量代码块的执行时间或任何需要高精度计时的场景。Stopwatch 提供了以下功能:

示例代码

using System;
using System.Diagnostics;

class Program
{
    static void Main()
    {
        Stopwatch stopwatch = new Stopwatch();
        stopwatch.Start();

        // 执行一些操作
        for (int i = 0; i < 1000000; i++)
        {
            // 模拟工作负载
        }

        stopwatch.Stop();
        Console.WriteLine("Elapsed time: " + stopwatch.Elapsed);
    }
}

Timer 类

Timer 类通常指的是 System.Timers.TimerSystem.Windows.Forms.Timer,它们用于在指定的时间间隔后执行代码。这些计时器主要用于定时任务,如每隔一段时间执行一次操作。

System.Timers.Timer

System.Timers.Timer 位于 System.Timers 命名空间,提供了一个服务器端的定时器,可以用于任何需要定时执行任务的场景,包括Windows服务。

示例代码

using System;
using System.Timers;

class Program
{
    static void Main()
    {
        Timer timer = new Timer(1000); // 设置定时器间隔为1000毫秒
        timer.Elapsed += (sender, e) => 
        {
            Console.WriteLine("Timer ticked at " + DateTime.Now);
            // 执行定时任务
        };
        timer.AutoReset = true; // 设置定时器自动重置
        timer.Enabled = true; // 启动定时器

        Console.WriteLine("Press any key to exit...");
        Console.ReadKey();
        timer.Dispose(); // 清理资源
    }
}

System.Windows.Forms.Timer

System.Windows.Forms.Timer 位于 System.Windows.Forms 命名空间,主要用于Windows Forms应用程序中,以指定的时间间隔触发事件。

using System;
using System.Windows.Forms;

class Program
{
    static void Main()
    {
        Timer timer = new Timer();
        timer.Interval = 1000; // 设置定时器间隔为1000毫秒
        timer.Tick += (sender, e) => 
        {
            Console.WriteLine("Timer ticked at " + DateTime.Now);
            // 执行定时任务
        };
        timer.Start(); // 启动定时器

        Console.WriteLine("Press any key to exit...");
        Console.ReadKey();
        timer.Stop(); // 停止定时器
    }
}

总结

根据你的具体需求,可以选择使用 Stopwatch 来测量时间间隔,或使用 Timer 来执行定时任务。

到此这篇关于C# 中Stopwatch和timer的实现示例的文章就介绍到这了,更多相关C# Stopwatch timer内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:
阅读全文