调用异步方法无需等待#2 [英] call async method without await #2

查看:123
本文介绍了调用异步方法无需等待#2的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个异步方法:

public async Task<bool> ValidateRequestAsync(string userName, string password)
{
    using (HttpClient client = new HttpClient())
    {
        HttpResponseMessage response = await client.GetAsync(url);
        string stringResponse = await response.Content.ReadAsStringAsync();

        return bool.Parse(stringResponse);
    }
}

我把这种方法是这样的:

I call this method like this:

bool isValid = await ValidateRequestAsync("user1", "pass1");

我可以调用从同步的方法同样的方法,而无需使用等待关键字?

例如:

public bool ValidateRequest(string userName, string password)
{
    return ValidateRequestAsync(userName, password).Result;
}

我认为这将导致死锁。

I think this will cause a deadlock.

修改

调用该方法类似于上面进行调用永远不会结束。 (该方法不到达结束了)

Calling the method like above makes the call never end. (The method doesn't reaches the end anymore)

推荐答案

如果你调用从单线程执行上下文,如UI线程异步方法,并等待结果同步,有死锁的概率很高。在你的榜样,即概率为100%

If you call an async method from a single threaded execution context, such as a UI thread, and wait for the result synchronously, there is a high probability for deadlock. In your example, that probability is 100%

想想吧。当你调用会发生什么

Think about it. What happens when you call

ValidateRequestAsync(userName, password).Result

您调用方法ValidateRequestAsync。在那里,你叫ReadAsStringAsync。其结果是,一个任务将返回到UI线程,并计划继续当它成为可用的UI线程上执行的延续。但当然,它永远不会变得可用,因为它在等待(阻塞)用于完成任务。但任务不能完成,因为它正在等待UI线程变得可用。僵局。

You call the method ValidateRequestAsync. In there you call ReadAsStringAsync. The result is that a task will be returned to the UI thread, with a continuation scheduled to continue executing on the UI thread when it becomes available. But of course, it will never become available, because it is waiting (blocked) for the task to finish. But the task can't finish, because it is waiting for the UI thread to become available. Deadlock.

有办法prevent这个僵局,但他们都是一个坏主意。只是为了完整性起见,下面可能的工作:

There are ways to prevent this deadlock, but they are all a Bad Idea. Just for completeness sake, the following might work:

Task.Run(async () => await ValidateRequestAsync(userName, password)).Result;

这是一个坏主意,因为你还是阻止你的UI线程等待,无所作为非常有用。

This is a bad idea, because you still block your UI thread waiting and doing nothing useful.

那么该如何解决呢?异步走一路。在UI线程上的原始调用者可能是一些事件处理程序,所以要确保是异步。

So what is the solution then? Go async all the way. The original caller on the UI thread is probably some event handler, so make sure that is async.

这篇关于调用异步方法无需等待#2的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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