Task.Start奇怪的行为 [英] Task.Start strange behavoir
问题描述
你好,我有下面的代码创建一个任务.然后将其设置为开始.
该任务旨在将响应添加到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
这篇关于Task.Start奇怪的行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!