c# - Why doesn't the status of a task change to canceled after cancel is called by CancellationTokenSource -
i made task count number, task receive cancel request after 5 seconds, after task cancelled checked status of task. status of task still running. why? sample code below:
var cts = new cancellationtokensource(); cts.cancelafter(5000);//request cancel after 5 seconds var newtask = task.factory.startnew(state => { try { int = 1; var token = (system.threading.cancellationtoken)state; while (true) { console.writeline(i); i++; thread.sleep(1000); token.throwifcancellationrequested(); } } catch { } { } }, cts.token, cts.token); try { newtask.wait(10000, cts.token); } catch { console.writeline("catch:"+ newtask.status);//the status running } console.readline();
there 2 problems code:
token.throwifcancellationrequested()name says, throws exception. since usetry/catchblock catch might return task. task state after "cancellation" won'tfaultedbecause framework doesn't see exception.- you using
waitsame cancellation token. means 5 seconds donewaitcancelled , catch block executed. @ time task may or may not cancelled.
what should getting rid of try/catch/finally in task's body , remove token call wait: newtask.wait(10000).
full code:
var cts = new cancellationtokensource(); cts.cancelafter(5000);//request cancel after 5 seconds var newtask = task.factory.startnew(state => { int = 1; var token = (system.threading.cancellationtoken)state; while (true) { console.writeline(i); i++; thread.sleep(1000); token.throwifcancellationrequested(); } }, cts.token, cts.token); try { newtask.wait(10000); } catch { console.writeline("catch:"+ newtask.status); } linqpad output:
1
2
3
4
5
catch:canceled