If you are using multiple threads to send data over a socket, it is recommended to use NetMQQueue to synchronize these requests.
I've attached the queue to a poller and I'm receiving queue.ReceiveReady
events. But in this event I get access to the underlying ConcurrentQueue instance. But I'm not sure what to do with this queue, should i take just one item out of it or should i try to empty it?
//Should I dequeue one item
private static void Queue_ReceiveReady(object sender, NetMQQueueEventArgs<NetMQMessage> e) {
var item = e.Queue.Dequeue();
socket.SendMultipartMessage(message);
}
//or all items available
private static void Queue_ReceiveReady(object sender, NetMQQueueEventArgs<NetMQMessage> e) {
NetMQMessage message;
while (e.Queue.TryDequeue(out message, TimeSpan.FromMilliseconds(10))) {
socket.SendMultipartMessage(message);
}
}
Now to my second question. I've checked the queue implementation and seen that it is just using a lock around the send method of underlying pair socket. So why should I use NetMQQueue, if i could simply use a lock around my send method too, reducing the overhead of an additional pair socket?
public void Send(NetMQMessage data) {
lock (lockobj) {
client.SendMultipartMessage(data);
}
}
I know, following the docs, I should add an additional inproc-Router socket and one DEALER for each thread, to synchronize outgoing calls. But I'm a little bit afraid of having too much overhead, compared to handling the synchronization myself. I expect up to 20 communication threads inside my application, two-way async communication.