I am implementing an interface method that is asynchronous (returns a task). However, my implementation is synchronous as needed. What is the best way to do this? Is there a built-in way to do this? Here are a few options that I am considering:
This is good because my code works synchronously. The downside is that if ComputeResult () fails or is canceled, my method throws instead of returning a failed task.
This more naturally applies to rejection and cancellation. However, this also introduces an unnecessary stream-hop.
Option 3: TaskCompletionSource
var tcs = new TaskCompletionSource<T>(); try { tcs.SetResult(ComputeResult()); } catch (OperationCanceledException) { tcs.SetCanceled(); } catch (Exception ex) { tcs.SetException(ex); } return tcs.Task;
This extends as a denial / cancellation AND excludes the stream-hop, but it is more detailed and complex.
source share