我编写了以下内容(一个简单的控制台应用程序)来测试我对C#中异步和等待的理解.
public class Program
{
    public static void Main(string[] args)
    {
        Console.WriteLine("Async result: " + getLengthFromWebsiteAsync());
    }
    public static async Task<int> getLengthFromWebsiteAsync()
    {
        HttpClient httpClient = new HttpClient();
        Task<string> sampleTask = httpClient.GetStringAsync("http://www.adobe.com");
        Console.WriteLine("Before the await: ");
        int lengthRequired = (await sampleTask).Length;
        Console.WriteLine("After the await: " + lengthRequired.ToString());
        return lengthRequired;
    }
以下是我运行的结果:
Before the await:
Async result: System.Threading.Tasks.Task'1[System.Int32]
我的问题是,是不是应该出现的"等待之后:"这一行?我是否在理解异步/等待流程的错误轨道上?
目前你正在开始手术 - 但它永远不会完成.在对任务执行任何操作之前,您的程序将终止.
由于这是一个控制台应用程序,因此无论如何都会在线程池线程上运行continuation,因此您可以更改代码以使Main方法阻塞,直到任务完成:
public static void Main(string[] args)
{
    Console.WriteLine("Async result: " + getLengthFromWebsiteAsync().Result);
}
通常,您应该非常小心使用Result和Wait()执行任务,因为您很容易导致死锁.(例如,在WinForms UI中执行上述操作是不安全的 - Result调用将阻止UI线程,直到任务完成...并且任务将等待UI线程可用于运行延续在await异步方法之后.)
| 归档时间: | 
 | 
| 查看次数: | 683 次 | 
| 最近记录: |