Click here to Skip to main content
15,885,745 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Dear All:

Code:

C#
While(tcpClient.Available >0)
{
  // todo: read contents
    Thread.Sleep(0);
}


The problem is

when call Thread.Sleep(0).

the tcpClient will be disposed.

the tcpClient.Available will throw exception.


Thanks.
Posted
Updated 20-Aug-12 6:17am
v2
Comments
[no name] 20-Aug-12 12:01pm    
That makes no sense at all. Calling Sleep will not dispose your connection for you.
Sergey Alexandrovich Kryukov 20-Aug-12 12:31pm    
Basically, you are right, but it might indirectly manifest already existing problem in a wrong code, if some race condition is present. Please see the explanation in my answer.
--SA
ridoy 20-Aug-12 12:24pm    
Question isn't clear..what you need to do here?

1 solution

The problem, if any, is somewhere else. Yes, I'm 100% sure.

I little clarification: Thread.Sleep(0) is not equivalent to "no operation" or the code where this line is missing. To best of my knowledge, it takes some time for the method call, it cause switching the calling thread off and preemption by some other thread (perhaps one-time), and the actual delay is some random delay more then zero. It could not possibly disrupt operation of your thread.

However, it can indirectly manifest some problem with some probability, if you whole code design is wrong due to race condition you might embed in your design. I prefer more descriptive term "incorrect dependency on the time of execution". Please see:
http://en.wikipedia.org/wiki/Race_condition[^].

To start the investigation, you should learn about threading and parallel design from this point of view. You did not provide us enough information to help you.

—SA
 
Share this answer
 
v2
Comments
AmitGajjar 21-Aug-12 1:03am    
5+ thanks for Thread.Sleep(0) explanation.
Sergey Alexandrovich Kryukov 21-Aug-12 14:19pm    
Thank you, Amit.
--SAq
Kuthuparakkal 21-Aug-12 1:32am    
great solution... so much to learn from you SA
Sergey Alexandrovich Kryukov 21-Aug-12 14:19pm    
Thank you very much for your nice words.
--SA
Sam_lin 21-Aug-12 11:55am    
i know what you mean, when call Thread.Sleep(0),There is a chance for opration system to switch another thread. That's said, another thread will close the socket.

i will check the whole code. Thanks.

But i want to make sure that "Thread.Sleep(0)" dosen't dispose any resource,right?

Thanks.

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