I have a bunch of classes that include an async method ExecuteAsync()
.
These classes return different types.
I need to invoke the ExecuteAsync()
method by reflection.
I know, from many other questions on SO, that if I knew the return type, I could just write, for example:
var task (Task<int>) obj.GetType().GetMethod("ExecuteAsync").Invoke(obj, null);
var result = await task;
I've got to the point where I can do this to get the task...
var method = p.GetType().GetMethod("ExecuteAsync");
var rt = method.ReturnType.Dump();
var task = Convert.ChangeType(method!.Invoke(p, null)!, rt);
but then var result = await task
won't compile as the compiler thinks task
is of type object?
and "object? is not awaitable".
Is there a way of executing/awaiting task
?
Am I going about this the wrong way?
If you start to use reflection you tend to need to continue using reflection. You should be able to cast your result to a Task
and await this. But to get the actual result you probably need to use reflection to access the Task.Result
property. So I would try something like this:
var resultTask = obj.GetType().GetMethod("ExecuteAsync").Invoke(obj, null);
await (Task)resultTask ;
var result = (int)resultTask.GetType().GetProperty("Result").GetValue(resultTask, null);
But I would only use solutions like this as the last resort, or for very quick and dirty code. In most cases other patterns can be used, and should be easier to maintain than using reflection.