如果我等待正在执行 ReadAsStringAsync() 的响应,我应该等待 ReadAsStringAsync() 吗? [英] Should I await ReadAsStringAsync() if I awaited the response that I'm performing ReadAsStringAsync() on?

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

问题描述

我是否应该等待 ReadAsStringAsync() 如果我等待我正在执行的响应ReadAsStringAsync()>?进一步澄清,以下之间有什么区别或正确的方法?它们实际上相同吗?

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);

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

推荐答案

你的第一个例子是正确的.第二个示例在异步操作期间不屈服.相反,通过获取 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.

此外,正如评论者 Scott Chamberlain 所指出的,通过阻塞当前线程可能会引入死锁的可能性.这取决于上下文,但是 await 的常见场景是在 UI 线程中使用该语句,并且 UI 线程需要保持对各种需求的响应,但包括能够实际处理等待操作的完成.

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.

如果避免第二种模式,即从一个你不知道的Task中检索Result属性的值已经完成,不仅可以保证高效使用您的线程中,您还可以确保避免这种常见的死锁陷阱.

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