简体   繁体   English

如何通过等待非通用任务获得任务结果

[英]How to get task result from awaiting a non generic task

I have the following method: 我有以下方法:

public async Task Execute()
{
    object previous = null;

    // _delegates is of type IReadOnlyCollection<Delegate>
    foreach (Delegate method in _delegates) 
    {
        Task executing = (Task) (previous != null
           ? method.DynamicInvoke(_repository, previous)
           : method.DynamicInvoke(_repository);

        await executing;

        // pseudo code here
        if (executing returns something)
           previous = executing.Result //<-- ?
        else
           previous = null;
    }
}

Basically I iterate over a list of delegates that I execute in order. 基本上我迭代我按顺序执行的委托列表。 Each delegate receives a repository as argument, and the return value of the previous delegate (if there was any). 每个委托都接收一个存储库作为参数,以及前一个委托的返回值(如果有的话)。

Some delegates return a Task and some return a Task<TResult> . 一些委托返回一个Task ,一些委托返回一个Task<TResult> If encountered with the latter, I want to store the TResult value in previous so I can pass it as an argument to the next delegate. 如果遇到后者,我想将TResult值存储在previous所以我可以将它作为参数传递给下一个委托。

Is there a way to achieve this? 有没有办法实现这个目标?

You can use Reflection to check if the type of the executing object is Task<T> and then read the "Result" property if so like this: 您可以使用Reflection来检查executing对象的类型是否为Task<T> ,然后读取“Result”属性,如果是这样的话:

var taskType = executing.GetType();

bool isTaskOfT =
    taskType.IsGenericType
    && taskType.GetGenericTypeDefinition() == typeof(Task<>);

if (isTaskOfT)
{
    object result = taskType.GetProperty("Result").GetValue(executing);
}

In if you need to add casting: 如果你需要添加施法:

if (executing returns something)
    previous = ((Task<object>)executing).Result
else
    previous = null;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM