markelof markelof - 1 month ago 6
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("www.something.com&page=" + n);
Console.WriteLine("Proccesing data from string... (Extract)");
}


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

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

Task.WaitAll(tasks);
}


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
Extract()
many times at once ?

Answer

The Task.WaitAll method's signature is:

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

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

Task.WaitAll(tasks.ToArray());

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

Comments