简体   繁体   中英

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> . 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.

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:

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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