Search code examples
c#aggregateexception

AggregateException Not Thrown in Task.Run()


I am trying to catch an AggregateException from a Task.Run() operation which intentionally fails, however an AggregateException is not thrown. Why?

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);
}

I expect the exception to be thrown but it is not. I also tried adding .Wait and still don't get the exception. The request is coming from a windows UI. Any ideas. Thanks.


Solution

  • This is how you enter the async/await from an EventHandler

    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);
    }