任务.开始奇怪的行为 [英] Task.Start strange behavior
问题描述
你好,我有下面的代码创建一个任务.然后将其设置为开始.该任务旨在将响应添加到 ConcurrentBag
列表中.但是等待似乎并不在等待所有任务完成.但是它们被标记为完成.列表中只有一项任务.使用 Task.Run
!
Hello I have the following code that creates a task. Then sets it to start.
The task is meant to add a response to the ConcurrentBag
list.
But the await does not seem to be waiting for all the tasks to complete. But they are being marked as completed. There is only one task in the list.
It works fine when using Task.Run
!
public async void RunT1()
{
DoesNotWork();
}
public async void RunT2()
{
DoesWork();
}
public async void DoesNotWork()
{
ConcurrentBag<string> concurrentBag = new ConcurrentBag<string>();
List<Task> taskList = new List<Task>();
Task task1 = new Task(async () =>
{
var xml = await LongWorkingMethod();
concurrentBag.Add(xml);
});
taskList.Add(task1);
taskList[0].Start();
await Task.WhenAll(taskList);
if (concurrentBag.Count > 0) //concurrentBag is empty,
//even though the task has finished
{
Debug.Print("success");
}
}
public async void DoesWork()
{
ConcurrentBag<string> concurrentBag = new ConcurrentBag<string>();
List<Task> taskList = new List<Task>();
Task task1 = Task.Run(async () =>
{
var xml = await LongWorkingMethod();
concurrentBag.Add(xml);
});
taskList.Add(task1);
await Task.WhenAll(taskList);
if (concurrentBag.Count > 0) //concurrentBag is NOT empty
{
Debug.Print("success");
}
}
推荐答案
几乎没有理由直接使用 Task
构造函数.
There's almost never a reason to use the Task
constructor directly.
在您的情况下, Task
构造函数不支持 async
委托(即 Action
而不是 Func< Task>
),当您将其中一个作为参数传递时,将其视为 async void
.
In your case the Task
constructor doesn't support an async
delegate (i.e. Action
instead of Func<Task>
) and when you pass one as a parameter is it treated as async void
.
这意味着调用 Start
即发即忘" 委托,由于没有 Task,它无法等待内部的异步操作完成
到 await
上.
That means that calling Start
"fires and forgets" the delegate and it can't wait for the asynchronous operation inside it to complete because there's no Task
to await
on.
var task = new Task(async () => await Task.Delay(1000));
task.Start();
await task; // completes immediately
在需要运行新的 Task
的情况下,请使用 Task.Run
.如您所见, Task.Run
确实支持 async
委托,并等待整个操作完成
Use Task.Run
in cases where you need to run a new Task
. Task.Run
, as you see, does support an async
delegate correctly and waits for the entire operation to complete
var task = Task.Run(async () => await Task.Delay(1000));
await task; // completes after 1000 milliseconds
这篇关于任务.开始奇怪的行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!