Timer in C#(1)

本文深入探讨了C#中的三种定时器:Windows Forms Timer, System.Threading Timer和System.Timers Timer,详细解释了它们的工作原理、特点及应用场景,并通过实例展示了如何在实际开发中使用这些定时器来解决特定问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

There are 3 different Timers in C#

  1. System.Windows.Forms.Timer
  2. System.Threading.Timer
  3. System.Timers.Timer

I will introduce them separately

1. System.Windows.Forms.Timer

A Timer is used to raise an event at user-defined intervals. This Windows timer is designed for a single-threaded environment where UI threads are used to perform processing. It requires that the user code have a UI message pump available and always operate from the same thread, or marshal the call onto another thread.

When you use this timer, use the Tick event to perform a polling operation or to display a splash screen for a specified period of time. Whenever the Enabled property is set to true and the Interval property is greater than zero, the Tick event is raised at intervals based on the Interval property setting.

This class provides methods to set the interval, and to start and stop the timer.

2. System.Threading.Timer

Use a TimerCallback delegate to specify the method you want the Timer to execute. The timer delegate is specified when the timer is constructed, and cannot be changed. The method does not execute on the thread that created the timer; it executes on a ThreadPool thread supplied by the system.

When you create a timer, you can specify an amount of time to wait before the first execution of the method (due time), and an amount of time to wait between subsequent executions (period). You can change these values, or disable the timer, using the Change method.

3. System.Timers.Timer
The Timer component is a server-based timer, which allows you to specify a recurring interval at which the Elapsed event is raised in your application. You can then handle this event to provide regular processing. For example, suppose you have a critical server that must be kept running 24 hours a day, 7 days a week. You could create a service that uses a Timer to periodically check the server and ensure that the system is up and running. If the system is not responding, the service could attempt to restart the server or notify an administrator.

The server-based Timer is designed for use with worker threads in a multithreaded environment. Server timers can move among threads to handle the raised Elapsed event, resulting in more accuracy than Windows timers in raising the event on time. For more information on server-based timers, see Introduction to Server-Based Timers[last part of this article].

The Timer component raises the Elapsed event, based on the value of the Interval property. You can handle this event to perform the processing you need. For example, suppose that you have an online sales application that continuously posts sales orders to a database. The service that compiles the instructions for shipping operates on a batch of orders rather than processing each order individually. You could use a Timer to start the batch processing every 30 minutes.

Server Timers, Windows Timers, and Thread Timers

 

There are three timer controls in Visual Studio and the .NET Framework:

  • A server-based timer, which you can add to the Toolbox
  • A Windows-based timer, which is always in the Toolbox
  • A thread timer, which is available programmatically

The Windows-based timer is optimized for use in Windows Forms applications. The server-based timer is an update of the traditional timer that has been optimized to run in a server environment. The thread timer is a simple, lightweight timer that uses callback methods instead of events and is served by thread-pool threads.

There are two types of threads in Win32 architecture: UI threads, and worker threads. UI threads sit idle most of the time and wait for messages to arrive in their message loops. Once they receive a message, they handle it and then wait for the next message to arrive. Alternatively, worker threads are used to perform background processing and do not use message loops. Both the Windows timer and the server-based timer run using an Interval property. The interval of the thread timer is set in the Timer constructor. The timers are designed for different purposes, as evidenced by their handling of threads:

The Windows timer is designed for a single-threaded environment where UI threads are used to perform processing. The accuracy of Windows timers is limited to 55 milliseconds. These traditional timers require that the user code have a UI message pump available and always operate from the same thread, or marshal the call onto another thread. For a COM component, this would be detrimental to performance.

The server-based timer is designed for use with worker threads in a multi-threaded environment. Because they use a different architecture, server-based timers have the potential to be much more accurate than Windows timers. Server timers can move among threads to handle the raised events.

The thread timer is useful in scenarios where messages are not pumped on the thread. For example, the Windows-based timer relies on operating-system timer support, and if you are not pumping messages on the thread, the event associated with your timer will not occur. The thread timer is more useful in this case.

 

Ref:http://msdn.microsoft.com/en-us/magazine/cc164015.aspx

转载于:https://www.cnblogs.com/whyandinside/archive/2009/08/07/1541331.html

### 使用 Timer 组件的示例 在 C# WinForms 中,`System.Windows.Forms.Timer` 是一种常用的计时器控件,用于定期执行某些操作。以下是关于如何配置和使用 `Timer` 的详细说明。 #### 创建并设置 Timer 控件 可以通过设计界面拖放或者通过代码创建 `Timer` 对象。以下是一个完整的代码示例: ```csharp using System; using System.Timers; // 如果需要更高精度可以引入此命名空间 using System.Windows.Forms; public class TimerExample : Form { private Label label; private Timer timer; public TimerExample() { label = new Label(); label.Text = "0"; label.AutoSize = true; label.Location = new System.Drawing.Point(10, 10); this.Controls.Add(label); // 初始化 Timer timer = new Timer(); timer.Interval = 1000; // 设置间隔时间为 1timer.Tick += OnTimedEvent; // 订阅 Tick 事件 timer.Start(); // 启动定时器 } private void OnTimedEvent(object sender, EventArgs e) { int count = int.Parse(label.Text); // 获取当前标签显示的时间 count++; // 增加时间 label.Text = count.ToString(); // 更新标签文字 } } // 主程序入口 static class Program { [STAThread] static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new TimerExample()); } } ``` 上述代码展示了如何初始化一个简单的计时器,并将其绑定到窗体上的一个 `Label` 上。每次触发 `Tick` 事件时,都会更新该标签的内容[^4]。 #### 关于异步资源请求处理 如果涉及到更复杂的场景,比如加载外部资源或网络数据,则可能需要用到回调函数来控制流程。例如,在 CEFSharp 库中,可以在资源请求之前调用特定方法以实现异步处理[^2]: ```csharp bool OnBeforeResourceLoad(IWebBrowser browser, IRequest request, IResponse response, ref bool cancel) { var callback = request.RequestCallback; if (callback != null && ShouldProcessAsynchronously(request)) { cancel = true; // 阻止默认行为 return CefReturnValue.ContinueAsync; // 返回继续状态 } return CefReturnValue.Continue; } ``` 虽然这段代码主要用于浏览器插件开发环境下的资源拦截功能,但它也体现了如何利用回调机制完成延迟任务管理[^5]。 #### 屏幕保护程序中的双缓冲技术应用 对于多显示器系统的屏幕保护应用程序来说,采用双缓冲绘图方式能够有效减少闪烁现象的发生。下面是从另一个角度出发的一个例子——基于 C# 实现带有多监视器支持以及平滑动画效果的自定义屏幕保护方案[^3]: ```csharp protected override CreateParams CreateParams { get { const int WS_EX_COMPOSITED = 0x02000000; CreateParams cp = base.CreateParams; cp.ExStyle |= WS_EX_COMPOSITED; // 开启硬件加速渲染模式 return cp; } } private void AnimateScreensaver(Graphics g) { foreach (Screen screen in Screen.AllScreens) { Rectangle bounds = screen.Bounds; using (Bitmap bufferImage = new Bitmap(bounds.Width, bounds.Height)) // 构建离屏缓存图像对象 { Graphics offscreenGraphics = Graphics.FromImage(bufferImage); DrawContent(offscreenGraphics); // 调用实际绘制逻辑 lock (this) { g.DrawImageUnscaledAndClipped(bufferImage, bounds); } // 将最终结果同步刷新至目标区域 } } } ``` 以上片段重点在于通过构建临时位图作为中间载体来进行预渲染工作,从而避免频繁重画引起视觉干扰问题。 ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值