in my current application, I send a UDP message, and resend after a second if the packet is not acknowledged by the server. For now I am using a volatile bool as a flag for termination, in the main thread, when ACK is recieved, the flag is set to true, as confirmed by breakpoints, yet after this, during the "if(done) break;" in my other thread, the flag is still false.
ThreadStart processTaskThread = delegate {
send(text);
};
new Thread(processTaskThread).Start();
void send(string text)
{
while (true)
{
byte[] data = Encoding.ASCII.GetBytes(text);
_socket.BeginSend(data, 0, data.Length, SocketFlags.None, (ar) =>
{
State so = (State)ar.AsyncState;
int bytes = _socket.EndSend(ar);
Console.WriteLine("SEND: {0}, {1}", bytes, text);
}, state);
Thread.Sleep(1000);
if (kill) break;
}
}
Now here the flag gets set to true correctly as confirmed by breakpoint:
private void Receive()
{
_socket.BeginReceiveFrom(state.buffer, 0, bufSize, SocketFlags.None, ref epFrom, recv = (ar) =>
{
State so = (State)ar.AsyncState;
int bytes = _socket.EndReceiveFrom(ar, ref epFrom);
_socket.BeginReceiveFrom(so.buffer, 0, bufSize, SocketFlags.None, ref epFrom, recv, so);
try {
string Rec = Encoding.ASCII.GetString(so.buffer, 0, bytes);
if (Rec.StartsWith("ACK:"))
{
kill = true;
return;
}
But back in the conditional in the thread loop it remains false. Any help appreciated.