2

I'm facing a problem as below:

  • I need to implement a traditional interface which will be called in a sync environment:

    public interface IWorker {
        int GetResult();
    }
    
  • I need to use a third party lib which uses async/await

    Task<int> ThirdPartyClass.WorkAsync();
    

How can I use the async method

    public class MyWorker : IWorker {
          public int GetResult()
          {
               // ??? how to use the async calls ???
               new ThirdPartyClass().WorkAsync();
          }
    }

I know there is a Result property, like int result = c.WorkAsync().Result;, but as far as I know it blocks the current thread and may cause dead locks. For example, calling an async method and use Result in a Winforms button event handler can cause dead lock problem.

Is there a better way to use async/await for such situation?

Zach
  • 5,715
  • 12
  • 47
  • 62
  • 4
    nope. you'll have to block, or make `GetResult` async. – Daniel A. White Aug 25 '16 at 14:41
  • 1
    It's always better to keep the async workflow async. You can go with a blocking Wait() on the task but that might end up in a deadlock. I'd rather suggest to have a async method like 'Task GetResultAsync()'. Or Callbacks are your best bet but in both cases, you'd end up modifying the IWorker. Better to add one than modify the existing one which is possibly used in a lot of places. – Swagata Prateek Aug 25 '16 at 14:43
  • There's several ways to do it, but if your method expects an `int` returned, then you *have* to wait for the task to finish. – Jonesopolis Aug 25 '16 at 14:45
  • @DanielA.White so all functions calling `GetResult` directly or indirectly must be async? – Zach Aug 25 '16 at 14:51
  • Most of the answers on the linked duplicate are horribly bad. [This](http://stackoverflow.com/a/5110698/263693) is the only good one. – Stephen Cleary Aug 26 '16 at 02:10

0 Answers0