Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to suspend a blocking thread without obsolete Thread.Suspend?

I have a thread that waits on TcpListener.AcceptTcpClient(), which blocks, which I want to suspend at times.

I've read about Monitor.Wait(...), but I only have experience working with mutexes and if the thread waits on a blocking method, it gets interesting.

Now that Thread.Suspend(...) is obsolete, how should I suspend the thread?

like image 788
Petrus Theron Avatar asked Nov 05 '22 06:11

Petrus Theron


1 Answers

This is not possible, it is an unsolvable race condition. The listener could have accepted a connection a microsecond before you want to suspend it. Closing the listener so it won't accept any connections is the only sure way.

Rethink your logic here. Whatever it is going to do with that connection that makes you want to stop it probably needs to be locked instead.

like image 111
Hans Passant Avatar answered Nov 09 '22 12:11

Hans Passant