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

查看:559
本文介绍了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.

尚不清楚,如果实际上要串行执行操作,为什么还要使用异步,但是我建议更改代码,使其看起来更像这样:

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天全站免登陆