c# - Can cancellation token be used at tasks method within? -
i've started working tasks , i've come things don't quite understand calling methods within task. have started new task this:
var ts = new cancellationtokensource(); var token = ts.token; task.run(() => control(), token); void control() { while(!token.iscancellationrequested) { token.throwifcancellationrequested(); switch(enum) { case something: startsomething(); break; } task.delay(50, token).wait(); } } now don't understand behavior of startsomething() once token has been cancelled. if startsomething() contains while loop, can use?
!token.iscancellationrequested and
token.throwifcancellationrequested(); as well, if cancellation exception being thrown inside startsomething() loop, instantly cancel task?
yes, can pass same token onto startsomething , exceptions bubble control , cancel task. if don't keep running if cancellationtokenwas cancelled until returns control tocontrol` observes token:
void startsomething(cancellationtoken token) { while (true) { token.throwifcancellationrequested(); // cancel task. // ... } } keep in mind though token.throwifcancellationrequested() raise exception , task canceled while !token.iscancellationrequested complete task without marking canceled.
Comments
Post a Comment