Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Task.Wait() not waiting for task to finish

Tags:

c#

async-await

I have a console app and I want to launch tasks one after the other.

Here is my code:

static void Main()
{
    string keywords = "Driving Schools,wedding services";
    List<string> kwl = keywords.Split(',').ToList();

    foreach(var kw in kwl)
    {
        Output("SEARCHING FOR: " + kw);
        Task t = new Task(() => Search(kw));
        t.Start();
        t.Wait();
    }

    Console.ReadLine();
}

static async void Search(string keyword)
{
    // code for searching
}

The problem is that it doesn't wait for the first task to finish executing. It fires off the subsequent tasks concurrently.

I am working with a rate limited API so I want to do one after the other.

Why is it not waiting for one search to finish before starting the next search?

like image 248
Guerrilla Avatar asked Jul 07 '16 09:07

Guerrilla


1 Answers

Your async method just returns void, which means there's no simple way of anything waiting for it to complete. (You should almost always avoid using async void methods. They're really only available for the sake of subscribing to events.) Your task just calls Search, and you're waiting for that "I've called the method" to complete... which it will pretty much immediately.

It's not clear why you're using async at all if you actually want to do things serially, but I'd suggest changing your code to look more like this:

static void Main()
{
    // No risk of deadlock, as a console app doesn't have a synchronization context
    RunSearches().Wait();
    Console.ReadLine();
}

static async Task RunSearches()
{
    string keywords = "Driving Schools,wedding services";
    List<string> kwl = keywords.Split(',').ToList();

    foreach(var kw in kwl)
    {
        Output("SEARCHING FOR: " + kw);
        await Search(kw);
    }             
}

static async Task Search(string keyword)
{
    // code for searching
}
like image 61
Jon Skeet Avatar answered Feb 14 '23 04:02

Jon Skeet