1

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.

Herb Ramos
  • 23
  • 4
  • 1
    You're not waiting on your task in `EnterWaitingRoom`, so the exception won't be thrown – Kevin Gosse Dec 12 '17 at 15:54
  • 1
    And when you await the AggregateException will be unwrapped to the inner exception => no AggregateException – Sir Rufo Dec 12 '17 at 15:55
  • I tried Task.Run(()=>...).Wait() and still not exception thrown. – Herb Ramos Dec 12 '17 at 16:00
  • Of course, you wait for the task that will return a task – Sir Rufo Dec 12 '17 at 16:01
  • @SirRufo You are correct that the `Task.Run` calls are inappropriate and shouldn't be used, but incorrect to state that there's a `Task`. It's inefficient, redundant, confusing, and wasteful, but it does return a `Task`. – Servy Dec 12 '17 at 16:01
  • @Sir Rufo - The EnterWaitingRoom function is called from a button click. It then calls an async method InvokeHubMethod. As far as I know this should work. – Herb Ramos Dec 12 '17 at 16:03
  • @Servy gotcha ;o) – Sir Rufo Dec 12 '17 at 16:18
  • @Servy I've removed Task.Run() and am just calling the async fuction this way InvokeHubMethod("HubMethod", new object[] { val }).ContinueWith(t=> { if (t.IsFaulted) { // Catch error here } }); This seems to work. – Herb Ramos Dec 12 '17 at 16:23

1 Answers1

0

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);
}
Sir Rufo
  • 18,395
  • 2
  • 39
  • 73