async / await上的MSDN示例 - 在等待呼叫后我是否可以到达断点?

时间:2016-02-23 11:01:50

标签: c# async-await

在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;
}

我的理解是await是一个抽象来自开发人员的异步流的构造 - 让他/她好像在同步工作。换句话说,在上面的代码中,我不关心getStringTask完成的方式和时间,我只关心它完成并使用它的结果。我希望在某个时候等待电话之后能够达到断点。

enter image description here

1 个答案:

答案 0 :(得分:6)

您可以从Console应用程序的Main方法调用异步方法,而无需等待异步方法完成。因此,您的流程会在您的任务有机会完成之前终止。

由于您无法将控制台应用程序的Main转换为异步(async Task)方法,因此您必须通过调用{{1}来阻止异步方法}或Wait

.Result

private static void Main(string[] args)
{ 
    AccessTheWebAsync().Wait();
}