Search code examples
c#asp.netexceptiontaskcontinuations

Exception handling in ContinueWith called infinitely


I'm calling an async method (Specifically: Microsoft.ServiceBus.Messaging.QueueClient.SendAsync()) and want to be able to handle the exceptions within.

One possibility I have come across is:

_queueClient.SendAsync(message).ContinueWith((t) =>
{
    Debug.WriteLine("Exception: " + t.Exception.InnerException.GetType().Name);
}, TaskContinuationOptions.OnlyOnFaulted);

However the ContinueWith seems to get called infinitely:

Exception: UnauthorizedAccessException
Exception: UnauthorizedAccessException
Exception: UnauthorizedAccessException
Exception: UnauthorizedAccessException
Exception: UnauthorizedAccessException
Exception: UnauthorizedAccessException
......................................
......etc

Any ideas why this happens and how to get around it?

Thanks


Solution

  • I was calling the send within a TraceListener which was then picking up the Debug.WriteLine and causing a loop.

    The implication is that a TraceListener listens for traces, but it seems it also listens to Debug messages as well.