Task.Start奇怪的行为 [英] Task.Start strange behavoir

查看:57
本文介绍了Task.Start奇怪的行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

你好,我有下面的代码创建一个任务.然后将其设置为开始. 该任务旨在将响应添加到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 即发即忘" 委托,并且由于没有Taskawait的存在,它不能等待内部的异步操作完成.

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆