Hi all,
I have a 3 different method what I need to do is using foreachloop I need to loopnthrough the methods based on types and use asymc await task.when all method to get all the response and show to the end user
How can I do that
Hi all,
I have a 3 different method what I need to do is using foreachloop I need to loopnthrough the methods based on types and use asymc await task.when all method to get all the response and show to the end user
How can I do that
Know the answer? Post it. Somebody with the same question will find it here.
Answer a question in the forums and earn +20 SHARP for every answer.
See unanswered questions
DevSocialUpcoming · 3rd editionAI Agents ConferenceDec 1–3, 2026Live onlineFree to attend5days leftRegister
Jignesh KumarRank #91 · 22.9K reputationPosted Jan 30, 2024, 4:54 AM EST
Hello Shiva,
You can use Task.WhenAll() as below in realtime.
using System; using System.Threading.Tasks; class Program { static async Task Main(string[] args) { // Call three asynchronous methods concurrently using Task.WhenAll await ExecuteAsyncAllMethods(); } static async Task ExecuteAsyncAllMethods() { // Start three asynchronous tasks Task task1 = Test1Async(); Task task2 = Test2Async(); Task task3 = Test3Async(); // Await all tasks to complete using Task.WhenAll await Task.WhenAll(task1, task2, task3); // Retrieve results from completed tasks int result1 = await task1; string result2 = await task2; bool result3 = await task3; // Output results Console.WriteLine($"Method 1 result: {result1}"); Console.WriteLine($"Method 2 result: {result2}"); Console.WriteLine($"Method 3 result: {result3}"); } static async Task Test1Async() { await Task.Delay(2000); // delay operation by 2 second return 10; } static async Task Test2Async() { await Task.Delay(1000); // delay operation by 1 second return "Hello"; } static async Task Test3Async() { await Task.Delay(6000); // delay operation by 6 seconds return true; } }siva nathanRank #1,694 · 899 reputationPosted Jan 30, 2024, 5:05 AM EST
Hi jignesh,
Why we are adding Tas.delay() in each and every method
May I know the use case
If we are not using that delay what will happen
Jignesh KumarRank #91 · 22.9K reputationPosted Jan 30, 2024, 5:18 AM EST
In above example that is use for testing purpose because we want to wait until all task completed. Our case after 6 seconds all methods should execute.
In your case just need to add all methods as task and call like my example should work.
Could you please share your code so can check on that?
siva nathanRank #1,694 · 899 reputationPosted Jan 30, 2024, 6:34 AM EST
Hi jignesh,
I called the 3 methods as like you mentioned but second and third methods are executed and returned the result Without first method returned the results
It is not waiting all the methods get executed