Tuesday, 15 January 2013

c# - CancellationTokenSource not behaving as expected -



c# - CancellationTokenSource not behaving as expected -

what's expected in case, if user cancels task hitting enter, other task hooked continuewith run, it's not case, per aggregateexception keeps thrown despite explicit handling in continuewith apparently not beingness executed. clarification on below please?

class programme { static void main(string[] args) { cancellationtokensource tokensource = new cancellationtokensource(); cancellationtoken token = tokensource.token; task task = task.run(() => { while (!token.iscancellationrequested) { console.write("*"); thread.sleep(1000); } }, token).continuewith((t) => { t.exception.handle((e) => true); console.writeline("you have canceled task"); }, taskcontinuationoptions.onlyoncanceled); console.writeline("press key cancel"); console.readline(); tokensource.cancel(); task.wait(); } }

let's start few facts: when pass cancellationtoken parameter task.run has effect if it's cancelled before task started running. if task running not canceled. to task canceled after has started running, need utilize cancellationtoken.throwifcancellationrequested, not cancellationtoken.iscancellationrequested. if task canceled, exception property doesn't hold exceptions , null. if continuation task not run reason, means canceled. a task contains exceptions + kid tasks (hence, aggregateexception). so happens in code:

the task starts running, because token not canceled. run until token gets canceled. after end continuation will not run because runs when preceding task canceled, , hasn't been. when wait task throw aggregateexception taskcanceledexception because continuation canceled (if remove continuation exception go away).

solution:

you need prepare task canceled, , remove (or null check) exception handling because there no exception:

var task = task.run(new action(() => { while (true) { token.throwifcancellationrequested(); console.write("*"); thread.sleep(1000); } }), token).continuewith( t => console.writeline("you have canceled task"), taskcontinuationoptions.onlyoncanceled);

c# .net multithreading task-parallel-library cancellation-token

No comments:

Post a Comment