我假设您在项目中使用clrzmq ZeroMq 包装器。据我所知,不可能使用 clrzmq 在简单的循环中接收非阻塞消息,它会无限期地阻塞一段特定的时间(通过向接收方法提供超时)或直到您收到一条消息.
但是,设置一个线程来定期轮询套接字并将传入消息推送到Queue
. 然后,您可以使用例如一个简单的 WinFormsTimer
定期将任何未决消息从该 (shared) 中取出Queue
。这是一个线程订阅者的工作示例:
public class ZeroMqSubscriber
{
private readonly ZmqContext _zmqContext;
private readonly ZmqSocket _zmqSocket;
private readonly Thread _workerThread;
private readonly ManualResetEvent _stopEvent = new ManualResetEvent(false);
private readonly object _locker = new object();
private readonly Queue<string> _queue = new Queue<string>();
public ZeroMqSubscriber(string endPoint)
{
_zmqContext = ZmqContext.Create();
_zmqSocket = _zmqContext.CreateSocket(SocketType.SUB);
_zmqSocket.Connect(endPoint);
_zmqSocket.SubscribeAll();
_workerThread = new Thread(ReceiveData);
_workerThread.Start();
}
public string[] GetMessages()
{
lock (_locker)
{
var messages = _queue.ToArray();
_queue.Clear();
return messages;
}
}
public void Stop()
{
_stopEvent.Set();
_workerThread.Join();
}
private void ReceiveData()
{
try
{
while (!_stopEvent.WaitOne(0))
{
var message = _zmqSocket.Receive(Encoding.UTF8,
new TimeSpan(0, 0, 0, 1));
if (string.IsNullOrEmpty(message))
continue;
lock (_locker)
_queue.Enqueue(message);
}
}
finally
{
_zmqSocket.Dispose();
_zmqContext.Dispose();
}
}
}
从Form
您只需定期轮询队列(此示例使用 aForms Timer
并将消息数据附加到 a Textbox
):
private readonly ZeroMqSubscriber _zeroMqSubscriber =
new ZeroMqSubscriber("tcp://127.0.0.1:5000");
void ReceiveTimerTick(object sender, EventArgs e)
{
var messages = _zeroMqSubscriber.GetMessages();
foreach (var message in messages)
_textbox.AppendText(message + Environment.NewLine);
}