并行运行异步方法 [英] Running async methods in parallel

查看:75
本文介绍了并行运行异步方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个异步方法GetExpensiveThing(),它执行一些昂贵的I/O工作.这就是我的使用方式:

I've got an async method, GetExpensiveThing(), which performs some expensive I/O work. This is how I am using it:

// Serial execution
public async Task<List<Thing>> GetThings()
{
    var first = await GetExpensiveThing();
    var second = await GetExpensiveThing();
    return new List<Thing>() { first, second };
}

但是由于这是一种昂贵的方法,所以我想并行执行这些调用.我本以为移动等待者将解决此问题:

But since it's an expensive method, I want to execute these calls in in parallel. I would have thought moving the awaits would have solved this:

// Serial execution
public async Task<List<Thing>> GetThings()
{
    var first = GetExpensiveThing();
    var second = GetExpensiveThing();
    return new List<Thing>() { await first, await second };
}

那是行不通的,所以我将它们包裹在一些任务中,这行得通:

That didn't work, so I wrapped them in some tasks and this works:

// Parallel execution
public async Task<List<Thing>> GetThings()
{
    var first = Task.Run(() =>
    {
        return GetExpensiveThing();
    });

    var second = Task.Run(() =>
    {
        return GetExpensiveThing();
    });

    return new List<Thing>() { first.Result, second.Result };
}

我什至尝试与等待和任务之间及其周围进行异步操作,但是这确实令人困惑,而且我没有运气.

I even tried playing around with awaits and async in and around the tasks, but it got really confusing and I had no luck.

是否有更好的并行运行异步方法,或者任务是一种很好的方法?

推荐答案

是否有更好的并行运行异步方法,或者任务是一种很好的方法?

Is there a better to run async methods in parallel, or are tasks a good approach?

是的,最佳"方法是利用 .NET小提琴,这应该可以帮助您了解一些信息.您的第二种方法实际上应该并行运行.我的小提琴证明了这一点!

Yes, the "best" approach is to utilize the Task.WhenAll method. However, your second approach should have ran in parallel. I have created a .NET Fiddle, this should help shed some light. Your second approach should actually be running in parallel. My fiddle proves this!

请考虑以下内容:

public Task<Thing[]> GetThingsAsync()
{
    var first = GetExpensiveThingAsync();
    var second = GetExpensiveThingAsync();

    return Task.WhenAll(first, second);
}

注意

最好使用异步"后缀,而不是GetThingsGetExpensiveThing-我们应该分别具有GetThingsAsyncGetExpensiveThingAsync-

It is preferred to use the "Async" suffix, instead of GetThings and GetExpensiveThing - we should have GetThingsAsync and GetExpensiveThingAsync respectively - source.

这篇关于并行运行异步方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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