C# 任务等待失败

C# 任务等待失败,c#,asynchronous,async-await,signalr,task,C#,Asynchronous,Async Await,Signalr,Task,我正在开始连接。首先我得到一个新的HubConnection实例, 之后,我创建了一个新的IHubProxy,名称为=“fileHub”,到目前为止还不错 我的问题是位于(或在)等待函数ContinueWith,我尝试启动连接,并在启动成功与否时写入控制台。 connection.Start()成功,并将“Connected”写入控制台。 在Console.WriteLine(“已连接”)之后添加的代码也可以顺利执行 但是任务永远不会完成,因此调用HandleSignalRAsync()方法的客

我正在开始连接。首先我得到一个新的HubConnection实例, 之后,我创建了一个新的IHubProxy,名称为=“fileHub”,到目前为止还不错

我的问题是位于(或在)等待函数ContinueWith,我尝试启动连接,并在启动成功与否时写入控制台。 connection.Start()成功,并将“Connected”写入控制台。 在Console.WriteLine(“已连接”)之后添加的代码也可以顺利执行

但是任务永远不会完成,因此调用HandleSignalRAsync()方法的客户端类等待完成失败

增加报税表;或任务。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");                        
                        }
                    });

}
我在解决方案的另一个类中使用TaskWaiter调用该方法:

Functions.HandleSignalRAsync().GetAwaiter().GetResult();
称之为:

Functions.HandleSignalRAsync().Wait();
也不管用

但任务从未完成

因为两个示例都同步阻塞,导致代码死锁。你不应该这样

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

await Functions.HandleSignalRAsync().ConfigureAwait(false);
如果您已经在使用
async await
,那么在
ContinueWith
中使用continuation样式没有任何好处,您只需将执行包装在
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);
}

既然您已经在使用
wait
,为什么还要使用
ContinueWith
wait
之后的代码是一个延续。如果要捕获异常,请将调用包装在异常处理程序中