简体   繁体   中英

What is a good alternative to await Task.Run executing an asyncronous lambda?

I'm in the process of upgrading old code using BackgroundWorker . Following a series of articles from Stephen Cleary on this matter, I think the ideal substitute in this case is Task.Run() .

Mine is a Windows Forms application. When a Form is constructed, different background operations are started and their results are collected in different event handlers, as per the BackgroundWorker pattern.

Now, my new methods follow the async/await pattern. I have some concerns about calling Task.Run() on an async methods.

private async void FormEventHandler(object sender, EventArgs e)
{
    Task.Run(async () => await AwaitableLongRunningTask_1());
    Task.Run(async () => await AwaitableLongRunningTask_2());
    //...
}

AwaitableLongRunningTask_1 and _2 needs to be async, since the calls they makes within the method body are to async methods.

I can't call them in a simple await succession:

private async void FormEventHandler(object sender, EventArgs e)
{
    await AwaitableLongRunningTask_1();
    await AwaitableLongRunningTask_2();
    //...
}

since they need to be started in parallel and they're obviously long running tasks spanning several seconds.

So my question is, do I need to refactor AwaitableLongRunningTasks to be non-async void, changing their internal behaviour like suggested here in "How to call asynchronous method from synchronous method" ? Are there better options I'm missing?

Use Task.WhenAll

private async void FormEventHandler(object sender, EventArgs e)
{
    await Task.WhenAll( 
            AwaitableLongRunningTask_1(), 
            AwaitableLongRunningTask_2());

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM