c# - Is there a simple way to return a task with an exception? -


my understanding return task.fromresult(foo) simple shorthand for:

var tcs = new taskcompletionsource<tfoo>(); tcs.setresult(foo); return tcs.task; 

is there equivalent task returns exception state?

var tcs = new taskcompletionsource<tfoo>(); tcs.setexception(new notsupportedexception()); // or whatever appropriate return tcs.task; 

i don't see task.fromexception. or more appropriate throw exception without returning task?

my understanding return task.fromresult(foo) simple shorthand for... [taskcompletionsource.setresult].

actually, task.fromresult doesn't use taskcompletionsource, its implementation simpler that.

is there equivalent task returns exception state?

i reckon taskcompletionsource best option this. this:

static task fromexasync(exception ex)  {     var task = new task(() => { throw ex; });     task.runsynchronously();     return task; } 

the exception not propagated outside returned task, until observed via await task or task.wait(), should desired behavior.

note if exception passed fromexasync active exception (i.e. has been thrown , caught elsewhere), re-throwing loose current stack trace , watson buckets information stored inside exception. there 2 ways of dealing it:

  • wrap exception aggregateexception. make original exception available aggregateexception.innerexception:

static task fromexasync(exception ex)  {     var task = new task(() => { throw new aggregateexception(ex); });     task.runsynchronously();     return task; } 
  • use exceptiondispatchinfo.capture flow active exception's state:

static task fromexasync(exception ex)  {     var ei = system.runtime.exceptionservices.exceptiondispatchinfo.capture(ex);     var task = new task(() => { ei.throw(); });     task.runsynchronously();     return task; } 

finally, perhaps simplest yet worst option (due overhead of state machine , compiler warning) throw async method:

static async task fromexasync(exception ex) {     throw ex; } 

Comments

Popular posts from this blog

user interface - How to replace the Python logo in a Tkinter-based Python GUI app? -

objective c - Greedy NSProgressIndicator Allocation -

how to set an OCR language in Google Drive -