concept Result in category .net

This is an excerpt from Manning's book Concurrency in .NET.
To write scalable software, you can’t have any blocked threads. In the previous code, when the task’s
Resultproperty is accessed because the task hasn’t yet finished running, the thread pool will most likely create a new thread. This increases resource consumption and hurts performance.
Listing 10.3
Task.Catchfunctionstatic Task<T> Catch<T, TError>(this Task<T> task, ➥ Func<TError, T> onError) where TError : Exception { var tcs = new TaskCompletionSource<T>(); #1 task.ContinueWith(innerTask => { if (innerTask.IsFaulted && innerTask?.Exception?.InnerException ➥ is TError) tcs.SetResult(onError((TError)innerTask.Exception. ➥ InnerException)); #2 else if (innerTask.IsCanceled) tcs.SetCanceled(); #2 else if (innerTask.IsFaulted) tcs.SetException(innerTask?.Exception?.InnerException ?? ➥ throw new InvalidOperationException()); #2 else tcs.SetResult(innerTask.Result); #2 }); return tcs.Task; } #1 An instance of TaskCompletionSource returns a Task type to keep consistency in the async model. #2 Sets the Result or Exception of the TaskCompletionSource based on the output of the Task
Result<'TSuccess, 'TError>can be used to handle errors in a functional style plus carry the cause of the potential failure. Figure 10.4 compares anullable primitive, the equivalentOptiontype, and theResulttype.Figure 10.4 Comparing a regular
nullable primitive (top row), theOptiontype (second row), and theResulttype (bottom row). TheResult Failureis generally used to wrap an error if something goes wrong.![]()
In certain programming languages, such as Haskell, the
Resultstructure is calledEither, which represents a logical separation between two values that would never occur at the same time. For example,Result<int, string>models two cases and can have either valueintorstring.