Skip to content

Instantly share code, notes, and snippets.

@SteveSandersonMS
Created May 24, 2018 10:54
Show Gist options
  • Save SteveSandersonMS/c3a205f19264486753183f5b75c5d6b5 to your computer and use it in GitHub Desktop.
Save SteveSandersonMS/c3a205f19264486753183f5b75c5d6b5 to your computer and use it in GitHub Desktop.
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