Monday, June 4, 2018

C#: how to use Async task in sync environment?

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 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?

No comments:

Post a Comment

plot explanation - Why did Peaches' mom hang on the tree? - Movies & TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...