[英]calling an async method inside a non-async method
I have a class that i'm inheriting from, and i have NO access to the base class. 我有一个我要继承的类,并且我没有访问基类的权限。 I'm overriding a method of that base class, and this method is not async, but i need it to call an async method i've created.
我正在重写该基类的方法,并且该方法不是异步的,但是我需要它来调用我创建的异步方法。 Like so:
像这样:
public class OverridingClass : BaseClass
{
public override bool TestMethod()
{
var res = engine.DoAsyncFunction().Result;
//do stuff with res value
}
}
is it better to use this method, where i take out the 'result' value, or should i add a new, synchronous method to the engine instead and ignore it's async function entirely, like so? 最好使用这种方法,在其中我提取“结果”值,还是应该向引擎添加一个新的同步方法,而完全忽略它的异步功能,像这样?
public class OverridingClass : BaseClass
{
public override bool TestMethod()
{
var res = engine.DoFunction();
//do stuff with res value
}
}
or is there something else i can do entirely to the overridden function to make it async? 还是我可以完全对覆盖的功能做一些其他事情以使其异步? If i try to make the overridden method:
如果我尝试做重写的方法:
public async override Task<bool> TestMethod()...
then i will get a compile error saying that the method doesn't match the base signature. 那么我会收到一个编译错误,说该方法与基本签名不匹配。
You can wrap it in a Task.Run()
like following, if you want it to be called asynchrounously: 如果希望它被异步调用,可以将其包装在
Task.Run()
,如下所示:
public override bool TestMethod()
{
var task = Task.Run(async () => {
return await engine.DoAsyncFunction();
});
var Result = task.Result; // use returned result from async method here
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.