在async/await上尝试MSDN的例子时,为什么我在await运算符之后无法达到断点?
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;
}
Run Code Online (Sandbox Code Playgroud)
我的理解是await是一个构造,它从开发人员那里抽象出异步流 - 让他/她好像在同步工作.换句话说,在上面的代码中,我不关心getStringTask完成的方式和时间,我只关心它的完成和使用它的结果.我希望在某个时候等待电话之后能够达到断点.
您可以从Console应用程序的Main方法调用异步方法,而无需等待异步方法完成.因此,您的流程会在您的任务有机会完成之前终止.
由于您无法将Console应用程序的Main转换为asynchronous(async Task)方法,因此您必须通过调用Wait或阻止异步方法.Result:
private static void Main(string[] args)
{
AccessTheWebAsync().Wait();
}
Run Code Online (Sandbox Code Playgroud)
要么
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
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
779 次 |
| 最近记录: |