Task.Wait() not waiting for task to finish

后端 未结 1 1633
灰色年华
灰色年华 2020-12-06 18:22

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,we         


        
相关标签:
1条回答
  • 2020-12-06 19:10

    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
    }
    
    0 讨论(0)
提交回复
热议问题