任务等待失败

Task await fails

我正在启动 HubConnection。首先我得到一个新的 HubConnection 实例, 之后我用 Name = "fileHub" 创建了一个新的 IHubProxy 到目前为止一切顺利。

我的问题出在可等待函数ContinueWith(或其中),我尝试启动连接,并在启动成功与否时写入控制台。 connection.Start() 成功并且 "Connected" 被写入控制台。 在 Console.WriteLine("Connected") 之后添加的代码也可以毫无问题地执行。

但是 任务永远不会完成,因此调用 HandleSignalRAsync() 方法的客户端 Class 等待完成未成功。

添加一个return;或 task.dispose();没有解决我的问题。

 public static async Task HandleSignalRAsync()
            {
                connection = new HubConnection("http://localhost:12754");

                myHub = connection.CreateHubProxy("fileHub");

                await connection.Start().ContinueWith(
                    task => 
                    {
                        if (task.IsFaulted)
                        {
                            var ex = task.Exception.GetBaseException();
                            Console.WriteLine("There was an error opening the connection: {0}", ex);
                        }
                        else
                        {
                            Console.WriteLine("Connected");                        
                        }
                    });

}

我在另一个 Class 的解决方案中使用 TaskAwaiter 调用方法:

Functions.HandleSignalRAsync().GetAwaiter().GetResult();

调用它:

Functions.HandleSignalRAsync().Wait();

也不行。

But the Task never finishes

因为两个示例都同步阻塞,导致您的代码死锁。你不应该 blocking on async code.

您需要正确地异步等待 HandleSignalRAsync:

await Functions.HandleSignalRAsync().ConfigureAwait(false);

如果您已经在使用 async-await,使用 ContinueWith 的延续样式没有任何优势,您可以简单地将执行包装在 try-catch 语句和 await里面:

try
{
    await connection.Start().ConfigureAwait(false);
    Console.WriteLine("Connected");
}
catch (Exception e)
{
    Console.WriteLine("There was an error opening the connection: {0}", e);
}