Task.Wait() 不等待任务完成 [英] Task.Wait() not waiting for task to finish

查看:37
本文介绍了Task.Wait() 不等待任务完成的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个控制台应用程序,我想一个接一个地启动任务.

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

这是我的代码:

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.

我正在使用一个速率受限的 API,所以我想一个接一个地做.

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?

推荐答案

你的 async 方法只返回 void,这意味着没有任何简单的方法等待它完全的.(您应该几乎总是避免使用 async void 方法.它们实际上只是为了订阅事件才可用.)您的任务只是调用 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.

如果你真的想串行地做事情,你为什么要使用 async 还不清楚,但我建议你把代码改成这样:

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
}

这篇关于Task.Wait() 不等待任务完成的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆