Page 128 - CSharp/C#
P. 128

Concurrent calls


        It is possible to await multiple calls concurrently by first invoking the awaitable tasks and then
        awaiting them.


         public async Task RunConcurrentTasks()
         {
             var firstTask = DoSomethingAsync();
             var secondTask = DoSomethingElseAsync();

             await firstTask;
             await secondTask;
         }


        Alternatively, Task.WhenAll can be used to group multiple tasks into a single Task, which completes
        when all of its passed tasks are complete.


         public async Task RunConcurrentTasks()
         {
             var firstTask = DoSomethingAsync();
             var secondTask = DoSomethingElseAsync();

             await Task.WhenAll(firstTask, secondTask);
         }


        You can also do this inside a loop, for example:


         List<Task> tasks = new List<Task>();
         while (something) {
             // do stuff
             Task someAsyncTask = someAsyncMethod();
             tasks.Add(someAsyncTask);
         }

         await Task.WhenAll(tasks);


        To get results from a task after awaiting multiple tasks with Task.WhenAll, simply await the task
        again. Since the task is already completed it will just return the result back


         var task1 = SomeOpAsync();
         var task2 = SomeOtherOpAsync();

         await Task.WhenAll(task1, task2);

         var result = await task2;


        Also, the Task.WhenAny can be used to execute multiple tasks in parallel, like the Task.WhenAll
        above, with the difference that this method will complete when any of the supplied tasks will be
        completed.


         public async Task RunConcurrentTasksWhenAny()
         {
             var firstTask = TaskOperation("#firstTask executed");



        https://riptutorial.com/                                                                               74
   123   124   125   126   127   128   129   130   131   132   133