简体   繁体   中英

Task.Wait() not waiting for task to finish

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?

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
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM