我应等待ReadAsStringAsync(),如果我期待已久的,我上执行ReadAsStringAsync()的反应如何? [英] Should I await ReadAsStringAsync() if I awaited the response that I'm performing ReadAsStringAsync() on?

查看:704
本文介绍了我应等待ReadAsStringAsync(),如果我期待已久的,我上执行ReadAsStringAsync()的反应如何?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我应该的await ReadAsStringAsync()如果我期待已久的的响应上我执行 ReadAsStringAsync()?为了进一步澄清,有什么区别或以下的正确方法吗?难道他们实际上是相同的?

  VAR响应=等待httpClient.GetAsync(东西);
VAR内容=等待response.Content.ReadAsStringAsync();
返回新AvailableViewingTimesMapper()地图(内容)。

  VAR响应=等待httpClient.GetAsync(东西);
VAR内容= response.Content.ReadAsStringAsync();
返回新AvailableViewingTimesMapper()地图(content.Result)。


解决方案

您第一个例子是正确的。第二示例中的异步操作期间不产生。相反,通过获取 content.Result 属性的值,将强制当前线程等待,直到异步操作已完成。

在另外,作为评议斯科特张伯伦指出,通过阻断当前线程有可能可以引入死锁的可能性。这取决于上下文,但等待一种常见的方案是使用的语句在UI线程,UI线程需要为各种需求保持敏感,但包括能够实际处理的等待操作的完成。

如果您避免第二种模式,即检索结果值工作你不'属性知道已完成,不仅可以确保有效地利用线程,也可以确保防止这种常见的僵局陷阱。

Should I await ReadAsStringAsync() if I awaited the response on which I'm performing ReadAsStringAsync()? To clarify further, what is the difference or the right way between the following? Are they effectively the same?

var response = await httpClient.GetAsync("something");
var content = await response.Content.ReadAsStringAsync();
return new AvailableViewingTimesMapper().Map(content);

OR

var response = await httpClient.GetAsync("something");
var content = response.Content.ReadAsStringAsync();
return new AvailableViewingTimesMapper().Map(content.Result);

解决方案

Your first example is the correct one. The second example does not yield during the asynchronous operation. Instead, by getting the value of the content.Result property, you force the current thread to wait until the asynchronous operation has completed.

In addition, as commenter Scott Chamberlain points out, by blocking the current thread it is possible you could introduce the possibility of deadlock. That depends on the context, but a common scenario for await is to use that statement in the UI thread, and the UI thread needs to remain responsive for a variety of needs, but including to be able to actually handle the completion of an awaited operation.

If you avoid the second pattern, i.e. retrieving the value of the Result property from a Task you don't know has completed, not only can you ensure efficient use of your threads, you can also ensure against this common deadlock trap.

这篇关于我应等待ReadAsStringAsync(),如果我期待已久的,我上执行ReadAsStringAsync()的反应如何?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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