Question

I'm using the NuGet package of ZeroMQ for Visual Studio. The version I'm using is 3.0.0-rc1.

I've been searching around for quite some time and still haven't been able to find an "elegant" solution to my issue. I am creating a server (ROUTER) socket and then basically waiting on any data to arrive on that socket. I do this by creating a poller and waiting in an infinite loop. My issue is trying to figure out how to break out of the call to Poll() when I am trying to shutdown the application. By the way, the code below is being done in a separate thread and I am passing in my context to the thread in order to create the Socket.

        using (ZmqSocket server = cntxt.CreateSocket(ZeroMQ.SocketType.ROUTER))
        {
            string strSocketAddress = String.Format("tcp://{0}:{1}", strIPAddress, nPort.ToString());

            try
            {
                server.Linger = TimeSpan.FromMilliseconds(1); ;

                server.Bind(strSocketAddress);

                server.ReceiveReady += server_ReceiveReady;

                ZeroMQ.Poller poller = new Poller(new List<ZmqSocket> {server});

                while (true)
                {
                    poller.Poll();
                }

            }
            catch (ZmqException zex)
            {
                server.Disconnect(strSocketAddress);

                server.Close();

                server.Dispose();
            }
        }

Everything here works as expected and I do receive the event whenever I receive data on the socket. But when I want to shutdown the app, I can't figure out how I am suppose to break out of the loop. I do understand that I can put a timeout on the poll and put some sort of flag in to say that I'm shutting down but I was hoping there would be a "better" solution than that.

What happens now is that when I am wanting to shut down, I call Terminate on the context but at that point the application hangs and never returns. I am assuming it is hanging because I still have a socket open. I also read that by setting the Linger flag to something really small that the socket should shutdown after the call to Terminate on the context but that isn't happening.

The reason I have the catch clause in is because when I was using version 2.0 and I called Dispose() on the context, I would receive an exception and I could gracefully get rid of the socket, but I'm no longer getting an exception with version 3.0.

So I was wondering if I'm just missing something? And if there is a more "elegant" approach to shutting down a socket that is in it's own thread waiting for messages?

Was it helpful?

Solution

Not really "elegant", but old and easy way is to actually connect to your listening socket from the same process (different thread), so you get the "event" and check that "shutdown" flag at that point.

Original name for this hack is "self-pipe trick".

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top