应用程序在运行异步任务时挂起

时间:2018-05-06 11:31:41

标签: c# asynchronous

我正在学习async / await并创建了一个虚拟控制台应用程序。当我尝试从异步方法获得结果时,程序就会挂起。不知道下面的代码有什么问题。

static void Main(string[] args)
{
    var task = Task.Factory.StartNew(() => 5);

    var x = TestAsync();
    //x.Start();
    Console.WriteLine(x.Result);
}

private static Task<int> CalculateValue()
{
        Console.WriteLine("In CalculateValue"); // This line is printed.
        Task<int> t = new Task<int>(GetValue); // The program hangs here.
        return t;
}

public static async Task<int> TestAsync()
{
        int result = await CalculateValue();
        return result;
}

private static int GetValue()
    {
        return 10;
    }

1 个答案:

答案 0 :(得分:2)

首先:

    Task<int> t = new Task<int>(GetValue); // The program hangs here.

不正确,程序实际挂起:

Console.WriteLine(x.Result);

.Result阻塞当前线程,直到任务x完成执行并返回结果。它永远不会完成,因为等待CalculateValue方法返回的任务,这是一项任务:

Task<int> t = new Task<int>(GetValue);

这就是所谓的冷酷任务&#39;这意味着它处于非活动状态。 开始一个热门的&#39;任务(基本上意味着启动任务)使用Task.Run方法:

Task<int> t = Task.Run(GetValue);

相关问题