c# - Force any task to be attached to parent -
i'm trying create extension method make task attached parent.
extension code:
internal static class taskhelpers { public static task attachtoparrent(this task task) { var tsc = new taskcompletionsource<task>(task.creationoptions & taskcreationoptions.attachedtoparent); task.continuewith(_ => tsc.trysetresult(task), taskcontinuationoptions.onlyonrantocompletion); task.continuewith(t => tsc.trysetexception(task.exception ?? new aggregateexception(new applicationexception("unknown"))), taskcontinuationoptions.onlyonfaulted); task.continuewith(t => tsc.trysetcanceled(), taskcontinuationoptions.onlyoncanceled); return tsc.task.unwrap(); } }
test code:
static void main(string[] args) { var cancellationtokensource = new cancellationtokensource(); var task1 = task.factory.startnew(() => { var task2 = task.factory.startnew(() => { (int = 0; < 5; i++) { if (!cancellationtokensource.iscancellationrequested) { console.writeline(i); thread.sleep(5000); } else { console.writeline("loop cancelled."); break; } } }, cancellationtokensource.token).attachtoparrent(); var task3 = task.factory.startnew(() => { (int = 0; < 5; i++) { if (!cancellationtokensource.iscancellationrequested) { console.writeline(i*10); thread.sleep(5000); } else { console.writeline("loop cancelled."); break; } } }, cancellationtokensource.token).attachtoparrent(); }, cancellationtokensource.token); console.writeline("enter cancel"); console.readkey(); cancellationtokensource.cancel(); console.writeline("waiting cancelled"); task1.wait(); console.writeline("task cancelled"); console.readkey(); }
parent task cancelled without waiting inner tasks complete. how can solve it, input i'm getting task i'm execution in parent dispatcher task. want execute task attached parent.
just supply taskcreationoptions.attachedtoparent
when calling task.factory.startnew
(only when creating child tasks):
var task2 = task.factory.startnew(..., cancellationtokensource.token, taskcreationoptions.attachedtoparent, taskscheduler.current);
for more information attached/detached tasks: see msdn
Comments
Post a Comment