Casting TResult in Task to System.Object

后端 未结 3 1908
误落风尘
误落风尘 2020-12-16 01:54

I am loading an assembly and calling a static method that will create a new object of type “MyClass1” (this type is specified at runtime) through reflection using MethodInfo

3条回答
  •  失恋的感觉
    2020-12-16 02:18

    As an enhancement to the accepted answer, you can avoid the blocking by awaiting the Task in between:

    var task = (Task)mi.Invoke(obj, null);
    await task;
    var result = task.GetType().GetProperty("Result").GetValue(task);
    

    Of course this will be properly asynchronous only if all methods up the call stack are marked async and you're using await instead of .Result everywhere.

提交回复
热议问题