What is the correct way to handle a part of code that you want to execute at the same time in C#? Each of these calls takes about 3 seconds each (we are making indexing improvements in our systems currently). How do I make these statements execute in parallel with results?
var properties = await _propertyService.GetPropertiesAsync("Fairfax, VA");
var ratings = await _ratingsService.GetRatingsAsync(12549);
CodePudding user response:
You can remove await
from invocation and await for result of Task.WhenAll
:
var propertiesTask = _propertyService.GetPropertiesAsync("Fairfax, VA");
var ratingsTask = _ratingsService.GetRatingsAsync(12549);
await Task.WhenAll(propertiesTask, ratingsTask);
var properties = propertiesTask.Result;
var ratings = ratingsTask.Result;
Or split method invocation and awaiting (which is usually less preferable option):
var propertiesTask = _propertyService.GetPropertiesAsync("Fairfax, VA");
var ratingsTask = _ratingsService.GetRatingsAsync(12549);
var properties = await propertiesTask;
var ratings = await ratingsTask;
CodePudding user response:
You can use Task.WhenAll
for that.
Task.WhenAll
will not block and can be awaited, yielding control back to the caller until all tasks finish (in contrast to Task.WaitAll
)
In terms of exceptions, If any of the prvided tasks completes in a faulted state, then the returned task will also complete in a Faulted state, where its exceptions will contain the aggregation of the set of the unwrapped exceptions from each of the supplied tasks.
var task1 = _propertyService.GetPropertiesAsync("Fairfax, VA");
var task2 = _ratingsService.GetRatingsAsync(12549);
await Task.WhenAll(task1, task2);