Skip to content

Instantly share code, notes, and snippets.

@Vidarls
Last active August 29, 2015 14:05
Show Gist options
  • Save Vidarls/101ce3506f5163564c43 to your computer and use it in GitHub Desktop.
Save Vidarls/101ce3506f5163564c43 to your computer and use it in GitHub Desktop.
Nemq issue
using NetMQ;
using System;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
namespace NetMQIssue
{
class Program
{
private const string Handler1Address = "tcp://127.0.0.1:2001";
private const string Handler2Address = "tcp://127.0.0.1:2002";
public static void Handler(NetMQContext ctx, string ownAddress, string otherAddress)
{
var counter = 0;
using (var socket = ctx.CreateRouterSocket())
{
using (var poller = new Poller(socket))
{
socket.Bind(ownAddress);
socket.ReceiveReady += (sender, args) =>
{
var m = args.Socket.ReceiveString();
counter++;
if (m == "stop")
{
Console.WriteLine("STOP RECEIVED");
poller.RemoveSocket(socket);
poller.Stop(false);
}
Console.WriteLine("{0} Thanx for {1} #{2}", ownAddress, m, counter);
};
var timer = new NetMQTimer(TimeSpan.FromMilliseconds(500));
timer.Elapsed += (sender, args) =>
{
using (var s2 = ctx.CreateDealerSocket())
{
s2.Connect(otherAddress);
s2.Send("Hello");
}
};
poller.AddTimer(timer);
poller.Start();
}
}
}
static void Main(string[] args)
{
using (var ctx = NetMQContext.Create())
{
var token = new CancellationTokenSource();
var h1 = Task.Factory.StartNew(() => Handler(ctx, Handler1Address, Handler2Address),token.Token,TaskCreationOptions.LongRunning, TaskScheduler.Default);
var h2 = Task.Factory.StartNew(() => Handler(ctx, Handler2Address, Handler1Address),token.Token,TaskCreationOptions.LongRunning, TaskScheduler.Default);
Console.WriteLine("Started");
Console.ReadLine();
Console.WriteLine("Attempting stop form main thread");
using (NetMQSocket stop1 = ctx.CreateDealerSocket(),
stop2 = ctx.CreateDealerSocket())
{
stop1.Connect(Handler1Address);
stop2.Connect(Handler2Address);
stop1.Send("stop");
stop2.Send("stop");
Console.WriteLine("Waiting..");
Task.WaitAll(new[] {h1, h2}, 10000);
Console.WriteLine("Done");
Console.ReadLine();
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment