在 Windows 服务中执行任务循环的最佳方法 [英] Best way to do a task looping in Windows Service
问题描述
我有一种方法可以向我们的客户发送一些短信,如下所示:
I have a method that send some SMS to our customers that look like below:
public void ProccessSmsQueue()
{
SmsDbContext context = new SmsDbContext();
ISmsProvider provider = new ZenviaProvider();
SmsManager manager = new SmsManager(context, provider);
try
{
manager.ProcessQueue();
}
catch (Exception ex)
{
EventLog.WriteEntry(ex.Message, EventLogEntryType.Error);
}
finally
{
context.Dispose();
}
}
protected override void OnStart(string[] args)
{
Task.Factory.StartNew(DoWork).ContinueWith( ??? )
}
所以,我有一些问题:
我不知道方法运行需要多长时间;
I don´t know how long it takes for the method run;
该方法可以抛出异常,我想写在EventLog上
The method can throw exceptions, that I want to write on EventLog
我想在循环中运行这个方法,每 10 分钟,但只能在最后一次执行完成之后.
I want to run this method in loop, every 10 min, but only after last execution finish.
我如何才能做到这一点?我想过使用ContinueWith()
,但我仍然对如何构建整个逻辑有疑问.
How I can achieve this? I thought about using ContinueWith()
, but I still have questions on how to build the entire logic.
推荐答案
你应该有一个接受 CancellationToken
的异步方法,这样它就知道什么时候停止,调用 ProccessSmsQueue
在 try-catch
块中并使用 Task.Delay
异步等待直到下一次需要运行:
You should have an async method that accepts a CancellationToken
so it knows when to stop, calls ProccessSmsQueue
in a try-catch
block and uses Task.Delay
to asynchronously wait until the next time it needs to run:
public async Task DoWorkAsync(CancellationToken token)
{
while (true)
{
try
{
ProccessSmsQueue();
}
catch (Exception e)
{
// Handle exception
}
await Task.Delay(TimeSpan.FromMinutes(10), token);
}
}
您可以在应用程序启动时调用此方法,并且 Task.Wait
返回的任务存在之前,以便您知道它已完成并且没有异常:
You can call this method when your application starts and Task.Wait
the returned task before existing so you know it completes and has no exceptions:
private Task _proccessSmsQueueTask;
private CancellationTokenSource _cancellationTokenSource;
protected override void OnStart(string[] args)
{
_cancellationTokenSource = new CancellationTokenSource();
_proccessSmsQueueTask = Task.Run(() => DoWorkAsync(_cancellationTokenSource.Token));
}
protected override void OnStop()
{
_cancellationTokenSource.Cancel();
try
{
_proccessSmsQueueTask.Wait();
}
catch (Exception e)
{
// handle exeption
}
}
这篇关于在 Windows 服务中执行任务循环的最佳方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!