在异步MSDN例如/等待 - 我不能在电话的await后达到破发点? [英] MSDN example on async/await - can't I reach the break point after the await call?
问题描述
在试图MSDN对异步例如/ AWAIT,我为什么不能在运营商的await后达到一个破发点?
In trying MSDN's example on async/await, why I can't reach a break point after the await operator ?
private static void Main(string[] args)
{
AccessTheWebAsync();
}
private async Task<int> AccessTheWebAsync()
{
// You need to add a reference to System.Net.Http to declare client.
HttpClient client = new HttpClient();
// GetStringAsync returns a Task<string>. That means that when you await the
// task you'll get a string (urlContents).
Task<string> getStringTask = client.GetStringAsync("http://msdn.microsoft.com");
// You can do work here that doesn't rely on the string from GetStringAsync.
/*** not relevant here ***/
//DoIndependentWork();
// The await operator suspends AccessTheWebAsync.
// - AccessTheWebAsync can't continue until getStringTask is complete.
// - Meanwhile, control returns to the caller of AccessTheWebAsync.
// - Control resumes here when getStringTask is complete.
// - The await operator then retrieves the string result from getStringTask.
string urlContents = await getStringTask;
// The return statement specifies an integer result.
// Any methods that are awaiting AccessTheWebAsync retrieve the length value.
return urlContents.Length;
}
我的理解是,AWAIT是从抽象开发商异步流结构 - 让他/她,仿佛同步工作。换句话说,在上述code,我不关心如何以及何时 getStringTask
结束,我只关心它完成,并使用其结果。我希望再能够在某个时候达到的await调用后破发点。
My understanding is that the await is a construct that abstracts the asynchronous flow from the developer - leaving him/her as if working synchronously. In other words, in the code above, I do not care about how and when the getStringTask
finishes, I care only about it finishing and using its results. I would expect then to be able to reach the break point after the await call at sometime.
推荐答案
您调用从控制台应用程序的主要方法,你的异步方法,无需等待异步方法来完成。这样一来,你的进程终止之前你的任务有机会完成。
You call your asynchronous method from a Console application's Main method without waiting for the async method to finish. As a result, your process terminates before your task has a chance to complete.
既然你不能转换控制台应用程序的主到异步(异步任务
)的方法,你必须阻止对异步方法,通过调用等待
或。结果
:
Since you can't convert a Console application's Main to an asynchronous (async Task
) method, you'll have to block on the asynchronous method, by calling Wait
or .Result
:
private static void Main(string[] args)
{
AccessTheWebAsync().Wait();
}
或
private static void Main(string[] args)
{
var webTask=AccessTheWebAsync();
//... do other work until the resuls is actually needed
var pageSize=webTask.Result;
//... now use the returned page size
}
这篇关于在异步MSDN例如/等待 - 我不能在电话的await后达到破发点?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!