Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get result of a non generic task

Tags:

c#

.net

Is there a way to get the result of a Task<T> when it has been downcast to the non generic Task? I know this is possible to do with Reflection, but is there a way to do it without? Maybe by the use of Expression? Here's an example of what I want to do:

RunResult RunTask(Task task)
{
    task.Wait();

    object result = ???;

    if (result is RunResult)
        return (RunResult)result;

    return RunResult.Success;
}

I know that I can accomplish this by having a different overload, but I do not like that the behavior changes depending on which overload is picked.

If the task doesn't have a result, then null is fine in this situation.

like image 408
jakobbotsch Avatar asked Dec 15 '22 22:12

jakobbotsch


1 Answers

This seems to be a Task<RunResult>, right? Then cast it to that type and extract the result.

If this guess of mine was wrong, you can use dynamic to quickly get to the value of the Result property.

((dynamic)myTask).Result

Now this resulting value is of type dynamic so I'm not sure how you want to extract data from it.

like image 87
usr Avatar answered Jan 02 '23 15:01

usr