Search code examples
c#multithreadingsocketsdebuggingnetmq

How to debug "Cannot close an uninitialised Msg" FaultException?


My app is crashing because of "Cannot close an uninitialised Msg" unhandled exception. This is probably due to access to socket from multiple threads.

And I have problem debugging this issue because when I review my code all access to socket is done in poller thread -- either in ReceiveReady event handler directly (which is run on poller thread by definition as I understand it) or in manually created Task (new Task(...)) and then started on poller thread (task.Start(poller)). So I don't see a place where it could happen.

Second problem is it is unhandled exception -- I wrap all sending/receiving in try-catch, yet the exception happen somewhere outside.

I am looking for ways how to effectively debug it and pinpoint the place in my code which misbehaves.


Code examples -- as I wrote I use only two "patterns":

Using poller thread directly (thanks to events fired on poller's thread):

 private async void OnMessageReceiveReady(object sender, NetMQSocketEventArgs args)
 {
     NetMQSocket socket = args.Socket;

     NetMQMessage mq_msg = socket.ReceiveMultipartMessage();
     ...

Switching to poller's thread from arbitrary thread:

Task sending = new Task(() =>
{
    foreach (NetMQFrame address in mq_envelope)
        socket.SendMoreFrame(address.ConvertToString());

    socket.SendFrame(response_data);
});
sending.Start(this.sharedPoller);
await sending.ConfigureAwait(false);

Solution

  • Unfortunately I didn't find any other method than trial&error and more logging.

    And the problem was with disposing sockets -- I have running poller (shared) and I tried to Remove and Dispose socket, however I found out that those two methods are asynchronous.

    As solution I group Remove and Dispose together in separate task and then schedule it to run in poller. Having task in hand I can call Wait on it and this way I achieve blocking, synchronous behaviour in my Dispose.