C
C#14mo ago
cypherpotato

✅ is there any way to cast Task into Task<object>?

so, i have this delegate function:
public delegate object RouterCallback(HttpRequest request);
public delegate object RouterCallback(HttpRequest request);
which some methods already implements it, and some of then are async that returns Task<something>, and i need that value inside that task. for non Task<T> methods i can have it using:
object actionResult = matchedRoute.Callback(request);
object actionResult = matchedRoute.Callback(request);
and fine, but if it is Task<something> i can only determine if it is an task using:
if (actionResult is Task taskResult)
if (actionResult is Task taskResult)
but it doens't has the .Result property since it's an Task and not Task<T> i can unsafely cast it and get it result using
if (actionResult is Task asyncResult)
{
asyncResult.Wait();

var valueTask = Unsafe.As<Task<object>>(asyncResult);
actionResult = valueTask.Result;
// do something with actionResult
}
if (actionResult is Task asyncResult)
{
asyncResult.Wait();

var valueTask = Unsafe.As<Task<object>>(asyncResult);
actionResult = valueTask.Result;
// do something with actionResult
}
but it only works when T is an reference-type and doens't works when T is an struct/value type object. so, I need to get the value of Task<T> actionResult when actionResult is a Task<T>, but I don't know what <T> is. how do I managed to get it?
using reflection to get the .Result property value requires a lot of resources and costs a lot of performance.
4 Replies
cypherpotato
cypherpotatoOP14mo ago
I emphasize: I don't have <T> from the Task from matchedRoute.Callback(request);
Aaron
Aaron14mo ago
using reflection is pretty much your only choice here unless you restrict them to a single (or small number of) possible T that you check individually and while that Unsafe.As may compile and seem to work, that is not something you are allowed to do, even for reference types
Accord
Accord14mo ago
Was this issue resolved? If so, run /close - otherwise I will mark this as stale and this post will be archived until there is new activity.
cypherpotato
cypherpotatoOP14mo ago
sure, thank you
Want results from more Discord servers?
Add your server