concept Result in category .net

appears as: Result, Result
Concurrency in .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 Result property 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.Catch function
static 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 a nullable primitive, the equivalent Option type, and the Result type.

Figure 10.4 Comparing a regular nullable primitive (top row), the Option type (second row), and the Result type (bottom row). The Result Failure is generally used to wrap an error if something goes wrong.

c10-04.png

In certain programming languages, such as Haskell, the Result structure is called Either, 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 value int or string.