【发布时间】:2015-10-01 11:22:22
【问题描述】:
我有一个 Windows 服务 (.NET 4.5.2),它应该在后台运行多个任务,而我想使用 System.Threading.Tasks 您正在考虑以下哪个实现的最佳实践?还是我完全错了?
场景 1:
protected override void OnStart(string[] args)
{
// Assume all tasks implemented the same way.
// I believe we shouldn't await the tasks in this scenario.
var token = this._cancellationTokenSource.Token;
this.RunTask1(token);
this.RunTask2(token);
this.RunTask3(token);
}
private async Task RunTask1(CancellationToken token)
{
var telebot = new Telebot("SOMETHING");
while( true )
{
// Some work...
// I/O dependent task.
var response = await telebot.GetUpdatesAsync(cancellationToken: token);
//
// Some other work
// maybe some database calls using EF async operators.
//
await Task.Delay(TimeSpan.FromSeconds(1), token);
}
}
场景 2:
protected override void OnStart(string[] args)
{
// Assume all tasks implemented the same way.
// I believe we shouldn't await the tasks in this scenario.
var token = this._cancellationTokenSource.Token;
this.RunTask1(token);
this.RunTask2(token);
this.RunTask3(token);
}
private void RunTask1(CancellationToken token)
{
Task.Factory.StartNew(async () =>
{
var telebot = new Telebot("SOMETHING");
while( true )
{
// Some work...
// I/O dependent task.
var response = await telebot.GetUpdatesAsync(cancellationToken: token);
//
// Some other work
// may be some database calls using EF async operators.
//
await Task.Delay(TimeSpan.FromSeconds(1), token);
}
}, token);
}
【问题讨论】:
-
将返回的任务分配到私有领域以感谢处置不是更好吗?
-
你可以使用 Task.Run(() => doStuff("hello world"));而不是 Task.Factory.StartNew()
-
@AvsenevSlava 据我所知,他们是平等的。
-
@SerG 我相信取消令牌可以用来结束任务。
-
但任务不会立即结束。那么异常呢?
标签: c# async-await task-parallel-library task