.net - Question about a argument in using Task -
guys, used use method task.factory.startnew(new action(()=>{}), cancellationtoken);
i have question second argument cancellationtoken. because cancellationtoken variable in method, in lambda expression, can cancel task using field msdn does; i'm not sure it's recommend. in case, second argument necessary here? passed in startnew method, not used. there scenario need use argument?
you need argument if want cancel task. if you're application doesn't support or require cancellation say
task.factory.startnew(() => { ... }); note cancellation cooperative code must poll cancellation , respond accordingly.
for example:
cancellationtokensource cts = new cancellationtokensource(); cancellationtoken token = cts.token; task mytask = task.factory.startnew(() => { (...) { token.throwifcancellationrequested(); // body of loop. } }, token); // ... elsewhere ... cts.cancel(); you have pass cancellation token method otherwise it's not attached task. code within method using token respond cancelation, either throwing or using iscancellationrequested shut down. although task cancel within lambda guess. task needs token too.
here's further clarification:
passing token startnew associates token task. has 2 primary benefits: 1) if token has cancellation requested prior task starting execute, task won't execute. rather transitioning running, it'll transition canceled. avoids costs of running task if canceled while running anyway. 2) if body of task monitoring cancellation token , throws operationcanceledexception containing token (which throwifcancellationrequested does), when task sees oce, checks whether oce's token matches task's token. if does, exception viewed acknowledgement of cooperative cancellation , task transitions canceled state (rather faulted state).
see general discussion of cancellation here:
http://msdn.microsoft.com/en-us/library/ff963549.aspx further discussion.
Comments
Post a Comment