Created
May 24, 2018 10:54
-
-
Save SteveSandersonMS/c3a205f19264486753183f5b75c5d6b5 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
class TaskResultUtil | |
{ | |
private static ConcurrentDictionary<Type, ITaskResultGetter> _cachedGetters = new ConcurrentDictionary<Type, ITaskResultGetter>(); | |
private interface ITaskResultGetter | |
{ | |
object GetResult(Task task); | |
} | |
private class TaskResultGetter<T> : ITaskResultGetter | |
{ | |
public object GetResult(Task task) => ((Task<T>)task).Result; | |
} | |
public static object GetTaskResult(Task task) | |
{ | |
var getter = _cachedGetters.GetOrAdd(task.GetType(), taskType => | |
{ | |
var resultType = taskType.GetGenericArguments().Single(); | |
return (ITaskResultGetter)Activator.CreateInstance( | |
typeof(TaskResultGetter<>).MakeGenericType(resultType)); | |
}); | |
return getter.GetResult(task); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment