I'm creating project using ZeroMQ. I need functions to start and to kill thread. Start function seems to work fine but there are problems with stop function.
private Thread _workerThread;
private object _locker = new object();
private bool _stop = false;
public void Start()
{
_workerThread = new Thread(RunZeroMqServer);
_workerThread.Start();
}
public void Stop()
{
lock (_locker)
{
_stop = true;
}
_workerThread.Join();
Console.WriteLine(_workerThread.ThreadState);
}
private void RunZeroMqServer()
{
using (var context = ZmqContext.Create())
using (ZmqSocket server = context.CreateSocket(SocketType.REP))
{
/*
var bindingAddress = new StringBuilder("tcp://");
bindingAddress.Append(_ipAddress);
bindingAddress.Append(":");
bindingAddress.Append(_port);
server.Bind(bindingAddress.ToString());
*/
//server.Bind("tcp://192.168.0.102:50000");
server.Bind("tcp://*:12345");
while (!_stop)
{
string message = server.Receive(Encoding.Unicode);
if (message == null) continue;
var response = ProcessMessage(message);
server.Send(response, Encoding.Unicode);
Thread.Sleep(100);
}
}
}
Maybe someone have any idea about this Stop() function, why it doesn't kill thread? I got hint that I should use Thread.MemoryBarrier and volatile but have no idea how it should works. There is also ProcessMessage() function to process messages, I just didn't copy it to don't litter :)