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.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…