Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p><strong>Cancelling AcceptTcpClient</strong></p> <p>Your best bet for cancelling the blocking <code>AcceptTcpClient</code> operation is to call <a href="http://msdn.microsoft.com/en-us/library/system.net.sockets.tcplistener.stop.aspx" rel="noreferrer">TcpListener.Stop</a> which will throw a <a href="http://msdn.microsoft.com/en-us/library/system.net.sockets.socketexception.aspx" rel="noreferrer">SocketException</a> that you can catch if you want to explicitly check that the operation was cancelled.</p> <pre><code> TcpListener serverSocket = new TcpListener ( serverAddr, serverPort ); ... try { TcpClient serverClient = serverSocket.AcceptTcpClient (); // do something } catch (SocketException e) { if ((e.SocketErrorCode == SocketError.Interrupted)) // a blocking listen has been cancelled } ... // somewhere else your code will stop the blocking listen: serverSocket.Stop(); </code></pre> <p>Whatever wants to call Stop on your TcpListener will need some level of access to it, so you would either scope it outside of your Listen method or wrap your listener logic inside of an object that manages the TcpListener and exposes Start and Stop methods (with Stop calling <code>TcpListener.Stop()</code>).</p> <p><strong>Async Termination</strong></p> <p>Because the accepted answer uses <code>Thread.Abort()</code> to terminate the thread it might be helpful to note here that the best way to terminate an asynchronous operation is by cooperative cancellation rather than a hard abort. </p> <p>In a cooperative model, the target operation can monitor a cancellation indicator which is signaled by the terminator. This allows the target to detect a cancellation request, clean up as needed, and then at an appropriate time communicate status of the termination back to the terminator. Without an approach like this, abrupt termination of the operation can leave the thread's resources and possibly even the hosting process or app domain in a corrupt state.</p> <p>From .NET 4.0 onward, the best way to implement this pattern is with a <a href="http://msdn.microsoft.com/en-us/library/dd384802.aspx" rel="noreferrer">CancellationToken</a>. When working with threads the token can be passed in as a parameter to the method executing on the thread. With Tasks, support for CancellationTokens is built into several of the <a href="http://msdn.microsoft.com/en-us/library/dd235664.aspx" rel="noreferrer">Task constructors</a>. Cancellation tokes are discussed in more detail in this <a href="http://msdn.microsoft.com/en-us/library/dd997364.aspx" rel="noreferrer">MSDN article.</a></p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload