c# - How to propagate a Task's Canceled status to a continuation task -


i using task parallel library in application. have task (let's call "dosomething") may canceled. whether task faulted, canceled, or completes successfully, have continuation attached task performs cleanup.

in code launches task, want return task object status (faulted, canceled, ran completion) reflects status of dosomething task, it's important task return not reflect status until continuation task executes.

here's example:

public task start(cancellationtoken token) {     var dosomethingtask = task.factory.startnew(dosomething                                                 , token);      var continuationtask = dosomethingtask.continuewith                 (                  (antecedent) =>                      {                          if (antecedent.isfaulted || antecedent.iscanceled)                          {                              //do failure-specific cleanup                          }     //do general cleanup without regard failure or success                       }                  );  //todo: how return task obj status reflect status of dosomethingtask, //but not transition status until continuationtask completes? } 

i use taskcompletionsource, seems kludgy. other ideas?

i think taskcompletionsource ideal scenario. i.e. trying return task signal of completion of work, manually control when , how task reports status. hide boiler plate required extension method this:

public static task<t> withcleanup<t>(this task<t> t, action<task<t>> cleanup) {     var cleanuptask = t.continuewith(cleanup);     var completion = new taskcompletionsource<t>();     cleanuptask.continuewith(_ => {         if(t.iscanceled) {             completion.setcanceled();         } else if(t.isfaulted) {             completion.setexception(t.exception);         } else {             completion.setresult(t.result);         }     });     return completion.task; } 

and call this:

var dosomethingtask = task.factory   .startnew<object>(dosomething, token)   .withcleanup(cleanup); 

the real caveat can't plain old task since there no non-generic taskcompletionsource.


Comments

Popular posts from this blog

java - SNMP4J General Variable Binding Error -

windows - Python Service Installation - "Could not find PythonClass entry" -

Determine if a XmlNode is empty or null in C#? -