I have two buttons that start and stop a 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");
}
Accept
is some method that reads from the TcpClient. My question is, before I stop the server by clicking the button, my server is blocked at
try {c = _listener.AcceptTcpClient();}
So how does clicking the cancel button kill the taskListener
? Without having a ManualResetEvent
or ManualResetEventSlim
? I am able to toggle between server shutdown and server restart. What's going on under the hood? I'm targeting .NET 4.0