为什么不是任务?WhenAll工作
本文关键字:WhenAll 工作 任务 为什么不 | 更新日期: 2023-09-27 18:16:39
这是我正在使用的一些代码,它触发了三个任务。我的Stop被调用,从输出来看,似乎任务在 Stop返回后完成了,这不是我所期望的。
这是Visual Studio 2013 with .NET 4.5.1
我尝试使用相同的AutoResetEvent工作如预期。
下面是它的输出:
Three tasks without auto reset
Starting...
FIRST
SECOND
THIRD
Running...
FIRST
FIRST
FIRST
SECOND
FIRST
FIRST
THIRD
...
SECOND
FIRST
Stopping...
THIRD
All done!
First done
Second done
Third done
我希望看到的是:
First done
Second done
Third done
All done!
下面是代码(我甚至在Console输出周围添加了锁,但没有什么不同):
public class ThreeTasksWithoutAutoResetEvent
{
private CancellationTokenSource cancellation;
private Task[] tasks;
private object obj = new object();
public ThreeTasksWithoutAutoResetEvent()
{
Console.WriteLine("Three tasks without auto reset");
cancellation = new CancellationTokenSource();
tasks = new Task[3];
Message("Starting...");
Start();
Message("Running...");
Thread.Sleep(3000);
Message("Stopping...");
Stop();
Message("All done!");
}
private void Start()
{
tasks[0] = this.First(cancellation.Token);
tasks[1] = this.Second(cancellation.Token);
tasks[2] = this.Third(cancellation.Token);
}
private async void Stop()
{
cancellation.Cancel();
await Task.WhenAll(tasks);
}
private async Task First(CancellationToken token)
{
await Task.Run(
() =>
{
while (!token.IsCancellationRequested)
{
Message("FIRST");
Thread.Sleep(100);
}
Message("First done");
}, token);
}
private async Task Second(CancellationToken token)
{
await Task.Run(
() =>
{
while (!token.IsCancellationRequested)
{
Message("SECOND");
Thread.Sleep(300);
}
Message("Second done");
}, token);
}
private async Task Third(CancellationToken token)
{
await Task.Run(
() =>
{
while (!token.IsCancellationRequested)
{
Message("THIRD");
Thread.Sleep(500);
}
Message("Third done");
}, token);
}
private void Message(string message)
{
lock (obj)
{
Console.WriteLine(message);
}
}
}
因为您没有等待Stop
方法完成。你不能等待一个async void方法。您需要返回一个Task,以便调用者可以等待/等待它完成。
private Task Stop()
{
cancellation.Cancel();
return Task.WhenAll(tasks);
}
则可以调用Stop().Wait();
而不是Stop
。它将等待WhenAll
完成。