简体   繁体   中英

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:

public override bool TestMethod()
{
    var task = Task.Run(async () => {

       return await engine.DoAsyncFunction();

    });

   var Result = task.Result; // use returned result from async method here
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM