long[] orderIds={10,11,12,13};
var orders= new List<Order>();
await Task.WhenAll(orderIds.Select(async (orderId) =>
{
var orderDetails = await GetOrderDetails(orderId);
if (orderDetails != null)
orders.Add(orderDetails);
}));
I am getting some wrong behavior with this, after deployement this code to server its working fine but on local sometimes it is adding all orders but sometime it missed some orders.
Can anybody please help to short out this, not sure what I am missing.
First, I recommend forcing enumeration of the tasks (e.g. an extra ToList() call) before sending them anywhere. You wouldn't want to accidentally enumerate the list more than once.
var tasks = orderIds.Select( orderId => GetOrderDetails(orderId) ).ToList();
Then await the tasks:
await Task.WhenAll( tasks );
And voila, your orders are ready.
var orders = tasks.Select( t => t.Result ).Where( o => o != null ).ToList();
BTW nothing is being mutated so you're completely thread-safe without any need for locks (assuming GetOrderDetails is thread-safe). This is one of the advantages of a functional approach to using linq and in general.
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