Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
390 views
in Technique[技术] by (71.8m points)

c# - Should I await ReadAsStringAsync() if I awaited the response that I'm performing ReadAsStringAsync() on?

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);
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...