C# .Net 调用异步方法并等待

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16153047/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 00:09:56  来源:igfitidea点击:

.Net Invoke async method and await

c#.netasync-await

提问by ajp

I have an ansyc method

我有一个 ansyc 方法

public Task<Car> GetCar()
{

}

I can call this method async and await:

我可以调用此方法异步并等待:

 Car car = await GetCar()

How can I invoke the method using MethodInfo.Invoke and await for the result asynchronously.

如何使用 MethodInfo.Invoke 调用方法并异步等待结果。

 MethodInfo method = obj.GetMethod("GetCar");
 method.Invoke( obj, null)

采纳答案by Stephen Cleary

You can invoke it normally and then awaitthe returned task:

可以正常调用然后await返回的任务:

Task<Car> result = (Task<Car>)method.Invoke(obj, null);
await result;