Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# - Exception Propagation Issue in AsyncCallback

Tags:

c#

.net

The following code is pretty self-explanatory and my question is very simple :
Why is AsyncCallback method "HandleConnect" not propagating exception to the "Connect" method
and how to propagate it ?

    public void Connect(IPEndPoint endpoint, IVfxIpcSession session)
    {
        try 
        {  
          ipcState.IpcSocket.BeginConnect(ipcState.IpcEndpoint, HandleConnect, ipcState);  
        }

        catch(Exception x) 
        { 
          ManageException(x.ToString()); //Never Caught, though "HandleConnect" blows a SocketException
        }
    }

    private void HandleConnect(IAsyncResult ar) 
    {
      // SocketException blows here, no propagation to method above is made. 
      // Initially there was a try/catch block that hided it and this is NOT GOOD AT ALL 
      // as I NEED TO KNOW when something goes wrong here.
       ipcState.IpcSocket.EndConnect(ar);  
    }


1 - I guess this is pretty normal behavior. But I would appreciate a comprehensive explanation of why is this happening this way and what happens exactly behind the hoods.

2 - Is there any (quick and simple) way to propagate the exception through my app ?

forewarning I know many dudes in here are very critical and I anticipate the comment "Why don't you put the ManageException directly in the "HandleConnect" Method. Well, to make a long story short, let's just say "I got my reasons" lol. I just posted a code sample here and I want to propagate this exception way further than that and do much more stuff than showed in other places in the "N-upper" code.

EDIT
As an aswer to a comment, I also tried this previously indeed, with no luck :

    private void HandleConnect(IAsyncResult ar) 
    {          
        try 
        {
          ipcState.IpcSocket.EndConnect(ar);  
        }

        catch(Exception x) 
        { 
          throw x; // Exception Blows here. It is NOT propagated.
        }
    }

My Solution : I ended up putting an Event Handler to whom every concerned code logic subscribes.
This way the exception is not just swallowed down nor just blows, but a notification is broadcasted.

 public event EventHandler<MyEventArgs> EventDispatch;
 private void HandleConnect(IAsyncResult ar) 
    {          
        try 
        {
          ipcState.IpcSocket.EndConnect(ar);  
        }

        catch(Exception x) 
        {               
           if (EventDispatch!= null)
           {
               EventDispatch(this, args);
           }
        }
    }

  //Priorly, I push subscriptions like that : 

  tcpConnector.EventDispatch += tcpConnector_EventDispatch;

  public void tcpConnector_EventDispatch(object sender, VfxTcpConnectorEventArgs args)
  {
        //Notify third parties, manage exception, etc.
  }

This is a little bit crooked, but it works fine

like image 635
Mehdi LAMRANI Avatar asked Nov 15 '11 13:11

Mehdi LAMRANI


1 Answers

When you use BeginConnect the connection is done asynchronously. You get the following chain of events:

  1. Connect "posts" a request to connect through BeginConnect.
  2. Connect method returns.
  3. The connection is done in the background.
  4. HandleConnect is called by the framework with the result of the connect.

When you reach step number 4, Connect has already returned so that try-catch block isn't active any more. This is the behavior you get when using asynchronous implementations.

The only reason you would have an exception caught in Connect is if BeginConnect fails to initiate the background connection task. This could e.g. be if BeginConnect validates the supplied arguments before initiating the background operation and throws an exception if they are not correct.

You can use the AppDomain.UnhandledException event to catch any unhandled exceptions in a central place. Once the exception reaches that level any form of recovery is probably hard to achieve, since the exception could be from anywhere. If you have a recovery method - catch the exception as close to the origin as possible. If you only log/inform the user - catching centrally in once place is often better.

like image 184
Anders Abel Avatar answered Oct 02 '22 00:10

Anders Abel