我正在尝试使用netmq(zeroMQ的端口)。这是我发现的问题。这是一个代码:
class Program
{
private static NetMQContext context;
static void Main(string[] args)
{
context = NetMQContext.Create();
using (var puller = context.CreatePullSocket())
{
puller.Bind("tcp://127.0.0.1:5651");
Thread.Sleep(500);
for (int i = 0; i < 5; i++)
{
Task.Run(new Action(PusheThread));
}
Console.WriteLine("any key to start receive");
Console.ReadKey();
Msg msg = new Msg();
msg.InitEmpty();
for (; puller.TryReceive(ref msg, new TimeSpan(0, 0, 5)); msg = new Msg(), msg.InitEmpty())
{
var s = Encoding.UTF8.GetString(msg.Data);
Console.WriteLine(s);
}
}
Console.WriteLine("any");
Console.ReadKey();
}
static void PusheThread()
{
var guid = Guid.NewGuid();
Console.WriteLine("started: " + guid);
using (var pusher = context.CreatePushSocket())
{
pusher.Connect("tcp://127.0.0.1:5651");
for (int i = 0; i < 5; i++)
{
pusher.Send("helo! " + guid);
}
}
}
}
如果我们运行此代码并在控制台中观看,我们会看到一些消息丢失。 像:
any key to start receive
started: 8aeca8e5-ed41-4055-ab72-750a0e61a680
started: 4211d77a-ad9f-40f1-9382-121156325128
started: bd735e75-2692-4abe-b8b1-fbddbe21e546
started: 6749d3bb-6b2b-4caa-b22e-755dba4d932d
started: 281ff59e-4430-4fc6-9435-4dc2c5e6015e
helo! 8aeca8e5-ed41-4055-ab72-750a0e61a680
helo! 6749d3bb-6b2b-4caa-b22e-755dba4d932d
helo! 8aeca8e5-ed41-4055-ab72-750a0e61a680
helo! 6749d3bb-6b2b-4caa-b22e-755dba4d932d
helo! 8aeca8e5-ed41-4055-ab72-750a0e61a680
helo! 6749d3bb-6b2b-4caa-b22e-755dba4d932d
helo! 8aeca8e5-ed41-4055-ab72-750a0e61a680
helo! 6749d3bb-6b2b-4caa-b22e-755dba4d932d
helo! 8aeca8e5-ed41-4055-ab72-750a0e61a680
helo! 6749d3bb-6b2b-4caa-b22e-755dba4d932d
any
我们看到来自4211d77a-ad9f-40f1-9382-121156325128
,bd735e75-2692-4abe-b8b1-fbddbe21e546
和其他人的消息在哪里。
多线程中的问题是什么?或者我做错了什么?感谢。
答案 0 :(得分:0)
问题出现在PusheThread
,您可以简单地将新创建的PushSocket
杀死为快速。
static void PusheThread()
{
var guid = Guid.NewGuid();
Console.WriteLine("started: " + guid);
using (var pusher = context.CreatePushSocket())
{
pusher.Connect("tcp://127.0.0.1:5651");
for (int i = 0; i < 5; i++)
{
pusher.Send("helo! " + guid);
}
Thread.Sleep(5000);
}
}
即使这不是一个可靠的解决方案,它应该证明问题是PushSocket
在发送消息之前由using
语句处理。
有些消息甚至只显示了NetMQ和ZeroMQ的速度:)