c# - Using Tasks with conditional continuations -
i'm little confused how use tasks conditional continuations.
if have task, , want continue tasks handle success , error, , wait on complete.
void functionthrows() {throw new exception("faulted");} static void mytest() { var taskthrows = task.factory.startnew(() => functionthrows()); var onsuccess = taskthrows.continuewith( prev => console.writeline("success"), taskcontinuationoptions.onlyonrantocompleted); var onerror = taskthrows.continuewith( prev => console.writeline(prev.exception), taskcontinuationoptions.onlyonfaulted); //so far, //this throws because onsuccess cancelled before started task.waitall(onsuccess, onerror); } is preferred way of doing task success/failure branching? also, how supposed join these tasks, suppose i've created long line of continuations, each having own error handling.
//for example var task1 = task.factory.startnew(() => ...) var task1error = task1.continuewith( //on faulted var task2 = task1.continuewith( //on success var task2error = task2.continuewith( //on faulted var task3 = task2.continuewith( //on success //etc calling waitall on these invariably throws, because of continuations cancelled due taskcontinuationoptions, , calling wait on cancelled task throws. how join these without getting "a task cancelled" exception"?
i think main problem you're telling 2 tasks "wait" call
task.waitall(onsuccess, onerror); the onsuccess , onerror continuations automatically setup , executed after antecedent task completes.
if replace task.waitall(...) taskthrows.start(); believe desired output.
here bit of example put together:
class program { static int divideby(int divisor) { thread.sleep(2000); return 10 / divisor; } static void main(string[] args) { const int value = 0; var exceptiontask = new task<int>(() => divideby(value)); exceptiontask.continuewith(result => console.writeline("faulted ..."), taskcontinuationoptions.onlyonfaulted | taskcontinuationoptions.attachedtoparent); exceptiontask.continuewith(result => console.writeline("success ..."), taskcontinuationoptions.onlyonrantocompletion | taskcontinuationoptions.attachedtoparent); exceptiontask.start(); try { exceptiontask.wait(); } catch (aggregateexception ex) { console.writeline("exception: {0}", ex.innerexception.message); } console.writeline("press <enter> continue ..."); console.readline(); } }
Comments
Post a Comment