Concurrent execution of async methods

江枫思渺然 提交于 2020-01-02 03:29:09

问题


Using the async/await model, I have a method which makes 3 different calls to a web service and then returns the union of the results.

var result1 = await myService.GetData(source1);
var result2 = await myService.GetData(source2);
var result3 = await myService.GetData(source3);

allResults = Union(result1, result2, result3);

Using typical await, these 3 calls will execute synchronously wrt each other. How would I go about letting them execute concurrently and join the results as they complete?


回答1:


How would I go about letting them execute in parallel and join the results as they complete?

The simplest approach is just to create all the tasks and then await them:

var task1 = myService.GetData(source1);
var task2 = myService.GetData(source2);
var task3 = myService.GetData(source3);

// Now everything's started, we can await them
var result1 = await task1;
var result1 = await task2;
var result1 = await task3;

You might also consider Task.WhenAll. You need to consider the possibility that more than one task will fail... with the above code you wouldn't observe the failure of task3 for example, if task2 fails - because your async method will propagate the exception from task2 before you await task3.

I'm not suggesting a particular strategy here, because it will depend on your exact scenario. You may only care about success/failure and logging one cause of failure, in which case the above code is fine. Otherwise, you could potentially attach continuations to the original tasks to log all exceptions, for example.




回答2:


As a more generic solution you can use the api I wrote below, it also allows you to define a real time throttling mechanism of max number of concurrent async requests.

The inputEnumerable will be the enumerable of your source and asyncProcessor is your async delegate (myservice.GetData in your example).

If the asyncProcessor - myservice.GetData - returns void or just a Task without any type, then you can simply update the api to reflect that. (just replace all Task<> references to Task)

    public static async Task<TOut[]> ForEachAsync<TIn, TOut>(
        IEnumerable<TIn> inputEnumerable,
        Func<TIn, Task<TOut>> asyncProcessor,
        int? maxDegreeOfParallelism = null)
    {
        IEnumerable<Task<TOut>> tasks;

        if (maxDegreeOfParallelism != null)
        {
            SemaphoreSlim throttler = new SemaphoreSlim(maxDegreeOfParallelism.Value, maxDegreeOfParallelism.Value);

            tasks = inputEnumerable.Select(
                async input =>
                    {
                        await throttler.WaitAsync();
                        try
                        {
                            return await asyncProcessor(input).ConfigureAwait(false);
                        }
                        finally
                        {
                            throttler.Release();
                        }
                    });
        }
        else
        {
            tasks = inputEnumerable.Select(asyncProcessor);
        }

        await Task.WhenAll(tasks);
    }



回答3:


You could use the Parallel class:

Parallel.Invoke(
() => result1 = myService.GetData(source1),
() => result2 = myService.GetData(source2),
() => result3 = myService.GetData(source3)
);

For more information visit: http://msdn.microsoft.com/en-us/library/system.threading.tasks.parallel(v=vs.110).aspx



来源:https://stackoverflow.com/questions/22117385/concurrent-execution-of-async-methods

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!