1

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 ?

Gilad Green
  • 36,708
  • 7
  • 61
  • 95
Demir Karic
  • 147
  • 11

2 Answers2

10

All you need is

Task.WaitAll(tasks.ToArray());

Different then WhenAll, It doesn't accepts IEnumerable<Task>.

https://msdn.microsoft.com/en-us/library/dd270695(v=vs.110).aspx

Your another option could be

await Task.WhenAll(tasks);
L.B
  • 114,136
  • 19
  • 178
  • 224
8

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

Community
  • 1
  • 1
Gilad Green
  • 36,708
  • 7
  • 61
  • 95
  • 2
    `in short WaitAll blocks the thread while WhenAll doesn't` No. `WhenAll` can block the current thread too.. `Task.WhenAll(tasks).Result` It is all related to how you use the tools – Eser Oct 11 '16 at 20:54
  • 1
    @Eser - yes but not because of `WhenAll` but because of the why you decide to use the `Task` it returns... Forgive me if it wasn't you but I think this is an unprofessional downvote... – Gilad Green Oct 11 '16 at 20:56