Task.Run() 中未抛出 AggregateException

AggregateException Not Thrown in Task.Run()

我试图从故意失败的 Task.Run() 操作中捕获 AggregateException,但是不会抛出 AggregateException。为什么?

public void EnterWaitingRoom(string val)
{
    try
    {
      Task.Run(() => InvokeHubMethod("HubMethod", 
         new object[] { val }));
    }
    catch (AggregateException ex)
    {
        // This exception is not caught
        throw ex;
    }
}

private async Task<object> InvokeHubMethod(string method, object[] args)
{
    return await Task.Run(() => _hubProxy.Invoke<object>(method, 
        args).Result);
}

我希望抛出异常,但没有。 我也尝试添加 .Wait 但仍然没有得到异常。 该请求来自 windows UI。 有任何想法吗。谢谢。

这就是您从 EventHandler

输入 async/await 的方式
public async void Button_Click(object sender, RoutedEventArgs args )
{
    object result = await EnterWaitingRoom( "whatever" );
}

private Task<object> EnterWaitingRoom(string val)
{
    return InvokeHubMethod(
        "HubMethod",
        new object[] { val } );
}

private Task<object> InvokeHubMethod(string method, object[] args)
{
    return _hubProxy.Invoke<object>(
        method, 
        args);
}