markelof markelof - 3 months ago 13
C# Question

Call same method many times at once

I have this simple method:

static void Extract()
Interlocked.Add(ref Program.n, 1);
Console.WriteLine("Currently on: " + n + " Page");
Console.WriteLine("Downloading String...Extract...");
WebClient client = new WebClient();
string html = client.DownloadString("" + n);
Console.WriteLine("Proccesing data from string... (Extract)");

I want to call method
few times at once and I tried this:

var tasks = new List<Task>();
for (int x = 0; x < 7; x++)
tasks.Add(Task.Factory.StartNew(new Action(Extract)));


But I get error

Severity Code Description Project File Line Suppression State
Error CS1503 Argument 1: cannot convert from
'System.Collections.Generic.List' to
'System.Threading.Tasks.Task' RecipeCommunity_Users C:\Users\xxx\AppData\Local\Temporary
Projects\Community_Users\Program.cs 24 Active

How I can call method
many times at once ?


The Task.WaitAll method's signature is:

public static void WaitAll(params Task[] tasks);

It receives a Task[] and not a list. Change to:


Depending on the usage it might be better to use WhenAll as L.B stated in his answer. Then use this way:

await Task.WhenAll(tasks);

See this question: WaitAll vs WhenAll. In short WaitAll blocks the thread while WhenAll itself doesn't.

As Eser menthioned in the comments the use of Task.WhenAll(tasks).Result will block the thread but that is due to blocking the task that WhenAll returns