Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ZeroMQ socket Recv() throws 'Context was terminated' exception - why and how to recover?

Tags:

c#

zeromq

Using a ZMQ.SocketType.REP (reply) messaging socket with ZeroMQ, I am receiving messages and then sending an "OK" message back.

For now, I'm trying this locally (sending/receiving messages from the same C# console app running on the same machine).

Fairly regularly (after about 1500 messages), the line:

var receivedBytes = _recvSocket.Recv();

... will throw an exception: Context was terminated

My question is, why does this happen, and how do you recover from it?

I have a System.Threading.Thread dedicated to running my "server-side" ZeroMQ reply socket, here is the loop that it runs:

    private static void MessagingLoopReceive(object state)
    {
        if (_zmqc == null)
        {
            _zmqc = new ZMQ.Context(1);
        }

        _recvSocket = _zmqc.Socket(ZMQ.SocketType.REP);
        _recvSocket.Bind("tcp://*:5556");

        while (true)
        {
            if (_queueStop)
            {
                break;
            }

            //Console.WriteLine("Server blocking for receive...");
            var receivedBytes = _recvSocket.Recv();

            if (receivedBytes != null && receivedBytes.Length > 0)
            {
                //Console.WriteLine("Server message received from client, sending OK");
                _recvSocket.Send("OK", Encoding.ASCII);
                //Console.WriteLine("Server OK sent, adding message to queue");
                _queuedMessages.Enqueue(receivedBytes);
            }
            else
            {
                Thread.Sleep(1);
            }
        }
    }
like image 803
Brandon Avatar asked Nov 05 '11 18:11

Brandon


1 Answers

It means that someone (the garbage collector?) have closed the context.

like image 161
sustrik Avatar answered Oct 14 '22 00:10

sustrik