为什么等待不等待? [英] Why does await not wait?

查看:111
本文介绍了为什么等待不等待?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的实际代码:

    async Task getData()
    {
        Thread.Sleep(5000);
        Console.WriteLine("Step 1");

        using (HttpClient api = new HttpClient()) 
            await api.GetAsync("http://google.com/").ContinueWith(
                (getTask) =>
                    Console.WriteLine(getTask.Result.StatusCode);
            );

        Console.WriteLine("Step 2");
    }

    private void button1_Click(object sender, EventArgs e)
    {
        Task<Task> task = new Task<Task>(getData);
        task.Start();
        task.Wait();
        Console.WriteLine("Step 3");
    }

我得到以下输出:

Step 1
Step 3
OK
Step 2

为什么Step 3不出现在Step 2之后?

如何使其按顺序工作,即仅在完成getData中的所有操作之前返回给getData的调用者?

How do I get it to work in sequence, ie to return to the caller of getData only until everything in getData is done?

推荐答案

您还应该将事件处理程序标记为async

You should also mark you event handler as async

private async Task button1_Click(object sender, EventArgs e)

await而不是Wait:

private async Task button1_Click(object sender, EventArgs e)
{
    await getData();

    Console.WriteLine("Step 3");
}

当我们使用异步/等待模式时,应该以这种方式进行操作,直到第一个方法启动它为止.否则,通过显式调用WaitResult,我们可能会遇到死锁问题.此外,显式调用这些方法会阻塞执行线程.因此,您放弃了使用async/await的主要好处,即不会阻塞正在执行的线程并在单独的线程上运行一些代码,一旦完成,就可以从停止的位置继续执行代码.

When we use the async/await pattern, we should go this way until the first method initiated it. Otherwise, by calling explicitly Wait or Result, we may run into deadlock issues. Furthermore, calling explicitly those methods you block the executing thread. So you drop the main benefit of using async/await, which is not blocking the executing thread and run on a separate thread some code and once this is done resume the execution of your code from where you stopped.

这篇关于为什么等待不等待?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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