Click here to Skip to main content
15,891,248 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
Hi, I'm just wondering if there is a better way of fixing this problem that I have. I'm sending two packets at the same time but for some reason only one client can receive both packets just fine at the same time the rest of the clients refuse to receive data. By adding the Thread.Sleep(1) it works just fine but just wanted to hear from you if there is a better way to solve it or should I keep it like this?

C#
Send(fs.GetFileCheckList(), 1);
Thread.Sleep(1);
Send(FileHashes, 0);

_buffer = new byte[1024];
client.BeginReceive(_buffer, 0, _buffer.Length, SocketFlags.None, new AsyncCallback(ReceiveCallback), client);
Posted

1 solution

For this purpose, not only sleeping is not a "better way"; it is totally unacceptable because it causes race condition: http://en.wikipedia.org/wiki/Race_condition[^].

Event if it works for you, it's just a matter of chance. It is not a legitimate way of thread synchronization. Sleeping has its uses, but this is beyond this question. Forget it for now.

If you really need one thread to wait for another one, you can use the class System.Threading.ManualResetEvent, which is merely a kind of the other class with specialized constructor, System.Threading.EventWaitHandle, which you also can use with System.Threading.EventResetMode.ManualReset:
http://msdn.microsoft.com/en-us/library/system.threading.manualresetevent%28v=vs.110%29.aspx[^],
http://msdn.microsoft.com/en-us/library/system.threading.eventwaithandle(v=vs.110).aspx[^].

I hope you can figure out how to use it from this MSDN documentation. When one thread calls EventWaitHandle.WaitOne, it is put to a special wait state which wastes no CPU time: the calling thread is switched off and never scheduled back to execution until it is waken up, which can be done by such conditions as abort, timeout, and, importantly, the call from other thread, which signals the same instance of EventWaitHandle with the call to EventWaitHandle.Set.

—SA
 
Share this answer
 
v5

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900