The problem
I have the following code:
Action function = async () => await Task.CompletedTask;
The problem with this code is that even though technically speaking it is an async delegate (one that can be awaited
) I cannot await it. In other words, the above could be written equivalently as
Func<Task> function = async () => await Task.CompletedTask;
The latter can be awaited, while the former cannot, even though this is the same method internally. Obviously, this is a contrived example, in my use case more complex code resides in a more complex codebase and it is not easy to spot all misusages.
The question
Can I check the actual type of function
at runtime and cast it to the correct one?
What I tried
Code below only throws if I declare function
as Func<Task>
(aka does not work as I expect it to)
Action function = async () => await Task.CompletedTask;
if (function.GetMethodInfo().ReturnType.IsEquivalentTo(typeof(Task)))
{
throw new Exception();
}
Code below does not even compile
Action function = async () => await Task.CompletedTask;
if (function is Func<Task> func)
{
}
Aucun commentaire:
Enregistrer un commentaire