我有一个 Windows 服务,我想每 10 秒创建一个文件。
我收到很多评论,Windows 服务中的 Timer 将是最佳选择。
我怎样才能做到这一点?
最佳答案
首先,选择正确的计时器。你想要 System.Timers.Timer
或 System.Threading.Timer
- 不要使用与 UI 框架相关联的框架(例如 System.Windows.Forms.Timer
或 DispatcherTimer
)。
定时器通常很简单
Elapsed
事件(或在构造时将回调传递给它),一切都会好起来的。
sample :
// System.Threading.Timer sample
using System;
using System.Threading;
class Test
{
static void Main()
{
TimerCallback callback = PerformTimerOperation;
Timer timer = new Timer(callback);
timer.Change(TimeSpan.Zero, TimeSpan.FromSeconds(1));
// Let the timer run for 10 seconds before the main
// thread exits and the process terminates
Thread.Sleep(10000);
}
static void PerformTimerOperation(object state)
{
Console.WriteLine("Timer ticked...");
}
}
// System.Timers.Timer example
using System;
using System.Threading;
using System.Timers;
// Disambiguate the meaning of "Timer"
using Timer = System.Timers.Timer;
class Test
{
static void Main()
{
Timer timer = new Timer();
timer.Elapsed += PerformTimerOperation;
timer.Interval = TimeSpan.FromSeconds(1).TotalMilliseconds;
timer.Start();
// Let the timer run for 10 seconds before the main
// thread exits and the process terminates
Thread.Sleep(10000);
}
static void PerformTimerOperation(object sender,
ElapsedEventArgs e)
{
Console.WriteLine("Timer ticked...");
}
}
我有更多关于 this page 的信息,虽然我很久没有更新了。
关于.net - Windows 服务中定时器的使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5495842/