question

TZacks-2728 avatar image
0 Votes"
TZacks-2728 asked TZacks-2728 answered

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

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

dotnet-csharp
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

Viorel-1 avatar image
0 Votes"
Viorel-1 answered Viorel-1 edited

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( ) );


5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

TimonYang-MSFT avatar image
2 Votes"
TimonYang-MSFT answered

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.

5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

TZacks-2728 avatar image
0 Votes"
TZacks-2728 answered

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);
 }
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.