我有一個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);
}
是不是更好返回任務分配給私人領域感激處置? – SerG
你可以使用Task.Run(()=> doStuff(「hello world」));而不是Task.Factory.StartNew() –
@AvsenevSlava據我所知,它們是平等的。 – mrtaikandi