wasAsked.

2 task to run together and how can we get all the result ?

Agiliad Technologies Pvt Ltd · Role not specified · technical

Published

Asked in 2026 · C#

Community answers

Posted by wasAsked editorial collection

Start both tasks without awaiting them individually, then await Task.WhenAll so they run concurrently. When both return the same type: Task<int> t1 = CountOrdersAsync(ct); Task<int> t2 = CountInvoicesAsync(ct); int[] results = await Task.WhenAll(t1, t2); // [orders, invoices] When they return different types: Task<User> userTask = GetUserAsync(id, ct); Task<List<Order>> ordersTask = GetOrdersAsync(id, ct); await Task.WhenAll(userTask, ordersTask); User user = userTask.Result; // safe: tasks already completed List<Order> orders = ordersTask.Result; // or: var user = await userTask; (completes immediately) The total time is roughly the slower of the two operations, not the sum. Error handling - If one or more tasks fail, await Task.WhenAll throws the first exception. To inspect all failures, keep the WhenAll task and check its Exception (an AggregateException): var all = Task.WhenAll(t1, t2); try { await all; } catch { foreach (var e in all.Exception!.InnerExceptions) logger.LogError(e, "Task failed"); } - Pass the same CancellationToken to both so you can cancel together, or use a linked token to cancel the other when one fails. Related options - Task.WhenAny: continue when the first task completes (timeouts, fastest-response patterns). - Task.WhenEach (.NET 9+): process tasks as each one completes. - Parallel.ForEachAsync: run many operations with a maximum degree of parallelism. - Avoid .Result or .Wait() before the tasks are complete; they block threads and can deadlock. Important caution with EF Core: one DbContext instance does not support parallel queries. Running two queries concurrently on the same context throws an exception. Use separate DbContext instances (IDbContextFactory) or run the queries sequentially. CPU-bound work: Task.Run(() => HeavyCalculation()) lets two CPU-heavy computations use different threads, but in ASP.NET Core prefer keeping request work I/O-bound and offload heavy CPU work to background processing.

Ravindra Wadile · · 0 likes

Sign in to add your answer

Related interview topics