2

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.

3
  • you want it to be called sync on UI thread or called async? Commented Feb 16, 2016 at 19:46
  • 3
    Personally I'd prefer the latter approach. If it's not "async all the way down" then there's potential for problems. And even getting around that and waiting on the task's result will only end up making it synchronous anyway, so it might as well be simply and explicitly synchronous. Commented Feb 16, 2016 at 19:46
  • 2
    @Phil: I describe a number of different approaches to this problem with pros and cons of each in an MSDN article. Commented Feb 17, 2016 at 13:21

1 Answer 1

6

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
}
Sign up to request clarification or add additional context in comments.

7 Comments

Honestly this totally slipped my mind. Thanks a bunch!
This is accomplishing nothing productive; it's doing what the OP was already doing, but wasting a whole bunch of additional resources in the process.
@Servy If the implementation of engine.DoAsyncFunction() yields to the caller with await and then you call Wait() on it, that's a potential deadlock. Firing up a new task is not pretty, but it won't deadlock.
@piedar But that's not the situation that he's in, as per the question. And even if it was, there are better ways of dealing with that problem.
@Servy you can post your thoughts, and it will make us learn the better approach as well. :)
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.