c# - How to tell if Task has been "observed"? -
this follow-up this question. i've read stephen toub's "tasks , unhandled exceptions" , think understand how tasks , exceptions work , "observed task" means. i cannot figure out how tell if task
has been observed or not. possible @ without using reflection?
i'd borrow @noseratio's code example:
static async void observe(task task) { await task; } // ... var taskobserved = false; var task = dosomething() try { bool ready = await dosomethingelse(); if (!ready) return null; var value = await dothirdthing(); // depends on dosomethingelse taskobserved = true; return value + await task; } { if (!taskobserved) observe(task); }
if tell whether task had been observed, made simpler , more readable:
static async void observe(task task) { if (!task.wasobserved) await task; } // ... var task = dosomething() try { bool ready = await dosomethingelse(); if (!ready) return null; var value = await dothirdthing(); // depends on dosomethingelse return value + await task; } { observe(task); }
tasks have no idea whether they've been awaited or not. it's kind of asking if integer knows if it's been added integer or not.
however, task's exception can observed, , whether exception has been observed in fact remembered task. it's important distinguish between unobserved exceptions , unawaited tasks. runtime has special logic unobserved task exceptions, not special unawaited tasks.
you should not write code depends on whether task has been awaited. if semantics dosomething
should awaited if result ignored (a odd - technically valid - requirement), code should suffice:
var task = dosomething(); try { bool ready = await dosomethingelse(); if (!ready) return null; var value = await dothirdthing(); // depends on dosomethingelse return value + await task; } { await task; }
on other hand, if semantics of dosomething
task can ignored if result isn't needed after (which far more case), code should suffice:
var task = dosomething(); bool ready = await dosomethingelse(); if (!ready) return null; var value = await dothirdthing(); // depends on dosomethingelse return value + await task;
no need mess around worrying whether task has been awaited.
Comments
Post a Comment