c# - TcpListener : how to stop listening while awainting AcceptTcpClientAsync() -
i don't know how close tcplistener while async method await incoming connections. found code on so, here code :
public class server { private tcplistener _server; private bool _active; public server() { _server = new tcplistener(ipaddress.any, 5555); } public async void startlistening() { _active = true; _server.start(); await acceptconnections(); } public void stoplistening() { _active = false; _server.stop(); } private async task acceptconnections() { while (_active) { var client = await _server.accepttcpclientasync(); dostuffwithclient(client); } } private void dostuffwithclient(tcpclient client) { // ... } }
and main :
static void main(string[] args) { var server = new server(); server.startlistening(); thread.sleep(5000); server.stoplistening(); console.read(); }
an exception throwed on line
await acceptconnections();
when call server.stoplistening(), object deleted.
so question is, how can cancel accepttcpclientasync() closing tcplistener properly.
while there complicated solution based on blog post stephen toub, there's simpler solution using builtin .net apis:
var cancellation = new cancellationtokensource(); await task.run(() => listener.accepttcpclientasync(), cancellation.token); // somewhere in thread cancellation.cancel();
this solution won't kill pending accept call. other solutions don't either , solution @ least shorter.
update: more complete example shows should happen after cancellation signaled:
var cancellation = new cancellationtokensource(); var listener = new tcplistener(ipaddress.any, 5555); listener.start(); try { while (true) { var client = await task.run( () => listener.accepttcpclientasync(), cancellation.token); // use client, pass cancellationtoken other blocking methods } } { listener.stop(); } // somewhere in thread cancellation.cancel();
Comments
Post a Comment