How to use async/await with a library that uses an event-based asynchronous pattern?

后端 未结 2 1009
你的背包
你的背包 2021-01-14 16:34

I use a library that has an asynchronous method called DoWork(...) that will raise a WorkDone event when the operation completes.

I would like to write a method that

2条回答
  •  粉色の甜心
    2021-01-14 17:17

    You can use TaskCompletionSource:

    public async Task SomeMethod()
    {
       var result = new TaskCompletionSource();
    
       library.WorkDone += (data) =>
                                    {
                                        result.SetResult(data);
                                    };
       library.DoWork();
    
       return await result.Task;
    }
    

提交回复
热议问题