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);
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With