多线程计时器
System.Threading.Timer - 最简单的多线程计时器。包含两个方法和一个构造函数。
示例:计时器调用 DataWrite 方法,该方法在五秒钟后写入“多线程执行…”,然后在此之后每秒写入一次,直到用户按 Enter 键:
using System;
using System.Threading;
class Program
{
static void Main()
{
// First interval = 5000ms; subsequent intervals = 1000ms
Timer timer = new Timer (DataWrite, "multithread executed...", 5000, 1000);
Console.ReadLine();
timer.Dispose(); // This both stops the timer and cleans up.
}
static void DataWrite (object data)
{
// This runs on a pooled thread
Console.WriteLine (data); // Writes "multithread executed..."
}
}
注意:将发布一个单独的部分来处理多线程定时器。
Change - 当你想要更改定时器间隔时,可以调用此方法。
Timeout.Infinite - 如果你想只开一次。在构造函数的最后一个参数中指定它。
System.Timers - .NET Framework 提供的另一个计时器类。它包裹了 System.Threading.Timer。
特征:
IComponent- 允许它安装在 Visual Studio 的 Designer 组件托盘中Interval属性而不是Change方法Elapsedevent而不是回调delegateEnabled属性启动和停止计时器(default value = false)Start&Stop方法如果你被Enabled属性弄糊涂(上面点)AutoReset- 表示经常性事件(default value = true)SynchronizingObject属性,带有Invoke和BeginInvoke方法,用于在 WPF 元素和 Windows 窗体控件上安全地调用方法
表示所有上述功能的示例:
using System;
using System.Timers; // Timers namespace rather than Threading
class SystemTimer
{
static void Main()
{
Timer timer = new Timer(); // Doesn't require any args
timer.Interval = 500;
timer.Elapsed += timer_Elapsed; // Uses an event instead of a delegate
timer.Start(); // Start the timer
Console.ReadLine();
timer.Stop(); // Stop the timer
Console.ReadLine();
timer.Start(); // Restart the timer
Console.ReadLine();
timer.Dispose(); // Permanently stop the timer
}
static void timer_Elapsed(object sender, EventArgs e)
{
Console.WriteLine ("Tick");
}
}
Multithreaded timers - 使用线程池允许一些线程为许多计时器提供服务。这意味着每次调用回调方法或 Elapsed 事件都可能在不同的线程上触发。
Elapsed - 此事件始终按时触发 - 无论之前的 Elapsed 事件是否已完成执行。因此,回调或事件处理程序必须是线程安全的。多线程定时器的准确性取决于操作系统,通常为 10-20 毫秒。
interop - 当你需要更高的准确度时,使用它并调用 Windows 多媒体计时器。这精度低至 1 毫秒,并在 winmm.dll 中定义。
timeBeginPeriod - 首先调用此信息通知操作系统你需要高计时准确度
timeSetEvent - 在 timeBeginPeriod 之后调用它来启动多媒体计时器。
timeKillEvent - 完成后调用此方法,这将停止计时器
timeEndPeriod - 调用此方法通知操作系统你不再需要高计时准确度。
你可以在互联网上找到使用多媒体计时器的完整示例,搜索关键字 dllimport winmm.dll timesetevent。