multithreading - Stop AcceptTcpClient on CancellationToken -
is there way in .net4 check cancellationtoken while accepting clients synchronously.
while (!token.iscancellationrequested) { //change somehow use check cancellation keep blocking tcpclient client = _tcplistener.accepttcpclient(); var client= new myclient(client); _clients.add(telemetryclient); } the best far, isn't clean enough:
while (!token.iscancellationrequested) { var accepttask = task<tcpclient>.factory.fromasync(_tcplistener.beginaccepttcpclient, _tcplistener.endaccepttcpclient, null); var tokentask = task.factory.startnew(() => { while (!token.iscancellationrequested) { thread.sleep(1000); } return; }, token); task.waitany(new task[] { accepttask ,tokentask}, token); if (token.iscancellationrequested) break; tcpclient client = accepttask.result;//_tcplistener.accepttcpclient(); var client = new myclient(client); _clients.add(telemetryclient); }
isn't sufficient task.waitany(accepttask, token)?
ie i'm not seeing why tokentask required.
also, if cancellation occurs , accepttask suffers exception, might find 'unobserved exception' situation arises. consider using taskscheduler.unobservedtaskexception catch (and ignore) those.
-mike
Comments
Post a Comment