Created
September 19, 2017 14:55
-
-
Save joshgarnett/cb104904a552136d2f5731f5cfc41a45 to your computer and use it in GitHub Desktop.
Adding support for piping task result to actor as a single message
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class TaskResult<T> { | |
public bool IsFailed { get; } | |
public T Result { get; } | |
public Exception Exception { get; } | |
public TaskResult(bool isFailed, T result, Exception ex) { | |
IsFailed = isFailed; | |
Result = result; | |
Exception = ex; | |
} | |
public static TaskResult<T> Success(T result) { | |
return new TaskResult<T>(false, result, null); | |
} | |
public static TaskResult<T> Failure(Exception ex) { | |
return new TaskResult<T>(true, default(T), ex); | |
} | |
} | |
public static class TaskExtensions { | |
public static void PipeResultTo<T>(this Task<object> taskToPipe, ICanTell recipient) { | |
taskToPipe.ContinueWith(tresult => { | |
TaskResult<T> message; | |
if (tresult.IsCanceled || tresult.IsFaulted) { | |
message = TaskResult<T>.Failure(tresult.Exception); | |
} | |
else { | |
if (tresult.Result is T) { | |
message = TaskResult<T>.Success((T) tresult.Result); | |
} | |
else { | |
message = TaskResult<T>.Failure(new Exception("Invalid type returned: " + tresult.GetType())); | |
} | |
} | |
recipient.Tell(message, ActorRefs.NoSender); | |
}, CancellationToken.None, TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Default); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment