c# How to add task to list and call all the tasks at last

T.Zacks 3,996 Reputation points
2021-04-28T18:10:48.27+00:00

I am looking for a sample code where i like to add multiple task to list one after one. after adding all need to call all the task and wait for all tasks to be completed. each task point to different function which may return string or void.

please help me with a small sample code. thanks

Developer technologies C#
0 comments No comments
{count} votes

Accepted answer
  1. Viorel 122.5K Reputation points
    2021-04-28T18:46:36.663+00:00

    Check an example that creates a list of three simple tasks, starts the execution potentially in parallel, and waits for termination:

    Action action1 = ( ) => Console.WriteLine( "This is task 1" );
    Action action2 = ( ) => Console.WriteLine( "This is task 2" );
    Action action3 = ( ) => Console.WriteLine( "This is task 3" );
    
    var list = new List<Action>( );
    
    list.Add( action1 );
    list.Add( action2 );
    list.Add( action3 );
    
    Parallel.Invoke( list.ToArray( ) );
    
    0 comments No comments

2 additional answers

Sort by: Most helpful
  1. Timon Yang-MSFT 9,606 Reputation points
    2021-04-29T07:36:15.39+00:00

    Are you looking for something like this?

    using System;  
    using System.Collections.Generic;  
    using System.Net.NetworkInformation;  
    using System.Threading;  
    using System.Threading.Tasks;  
      
    public class Example  
    {  
       public static void Main()  
       {  
          int failed = 0;  
          var tasks = new List<Task>();  
          String[] urls = { "www.adatum.com", "www.cohovineyard.com",  
                            "www.cohowinery.com", "www.northwindtraders.com",  
                            "www.contoso.com" };  
            
          foreach (var value in urls) {  
             var url = value;  
             tasks.Add(Task.Run( () => { var png = new Ping();  
                                         try {  
                                            var reply = png.Send(url);  
                                            if (! (reply.Status == IPStatus.Success)) {  
                                               Interlocked.Increment(ref failed);  
                                               throw new TimeoutException("Unable to reach " + url + ".");  
                                            }  
                                         }  
                                         catch (PingException) {  
                                            Interlocked.Increment(ref failed);  
                                            throw;  
                                         }  
                                       }));  
          }  
          Task t = Task.WhenAll(tasks);  
          try {  
             t.Wait();  
          }  
          catch {}     
      
          if (t.Status == TaskStatus.RanToCompletion)  
             Console.WriteLine("All ping attempts succeeded.");  
          else if (t.Status == TaskStatus.Faulted)  
             Console.WriteLine("{0} ping attempts failed", failed);        
       }  
    }  
    // The example displays output like the following:  
    //       5 ping attempts failed  
    

    Task.WhenAll Method


    If the response is helpful, please click "Accept Answer" and upvote it.
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    3 people found this answer helpful.
    0 comments No comments

  2. T.Zacks 3,996 Reputation points
    2021-05-01T07:24:58.307+00:00

    I have done the job this way.

    private async void button1_Click(object sender, EventArgs e)
    {
        IProgress<string> progress = new Progress<string>(str =>
        {
            textBox1.Text += str+System.Environment.NewLine;
        });
    
        await Run(progress);
    }
    
    public async Task GetData(int i, IProgress<string> progress)
    {
        progress.Report("Task created "+i.ToString());
        await Task.Delay(new Random().Next(1000, 10000));
        progress.Report("Task completed "+i.ToString());
    }
    
    private async Task Run(IProgress<string> progress)
    {
        List<Task> tasks = new List<Task>();
        for (int i = 0; i < 5; i++)
        {
            tasks.Add(GetData(i + 1, progress));
        }
    
        await Task.WhenAll(tasks);
    }
    
    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.