Monday 4 June 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

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...