Cancel token in the lock task under the hood

I have two buttons that start and stop TcpListener.

private void buttonStartServer_Click(object sender, EventArgs e)
{
    ThreadPool.SetMinThreads(50, 50);
    IPAddress ipAddress = IPAddress.Parse("127.0.0.1");
    _listener = new TcpListener(ipAddress, 5000);
    cancelSource = new CancellationTokenSource();
    CancellationToken token = cancelSource.Token;
    var taskListener = Task.Factory.StartNew(
                        (t) => Listener(token),token,TaskCreationOptions.LongRunning);
}

void Listener(CancellationToken token)
{
    _listener.Start();
    while (!token.IsCancellationRequested)
    {
        TcpClient c;
        try
        {
            c = _listener.AcceptTcpClient();
        }
        catch
        {
            break;
        }
        Task t = Task.Factory.StartNew(() => Accept(c))
            .ContinueWith(ant => richTextBoxMessage.AppendText(ant.Result), _uiScheduler);
    }
}

private void buttonStopServer_Click(object sender, EventArgs e)
{
    cancelSource.Cancel();
    _listener.Stop();
    richTextBoxMessage.AppendText("Server shutdown");
}

Acceptis a method that is read from TcpClient. My question is that before I stop the server by clicking the button, my server is locked in

try {c = _listener.AcceptTcpClient();}

So how taskListenerdoes pressing the cancel button kill ? Without availability ManualResetEventor ManualResetEventSlim? I can switch between server shutdown and server reboot. What happens under the hood? I'm aiming for.NET 4.0

+4
source share
1 answer

So how does hitting the cancel button kill taskListener?

TcpListener.Stop , Socket SocketException, catch all, .

( ):

. . , SocketException.. .

, catch:

TcpClient c;
try
{
    c = _listener.AcceptTcpClient();
}
catch (SocketException e)
{
    Debug.WriteLine("Socket exception was raised: {0}", e);
    if (e.SocketErrorCode == SocketError.Interrupted)
        Debug.WriteLine("Blocking listen was interrupted");
}
+3

Source: https://habr.com/ru/post/1619473/


All Articles