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

后端 未结 2 986
你的背包
你的背包 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<Result> SomeMethod()
    {
       var result = new TaskCompletionSource<Result>();
    
       library.WorkDone += (data) =>
                                    {
                                        result.SetResult(data);
                                    };
       library.DoWork();
    
       return await result.Task;
    }
    
    0 讨论(0)
  • 2021-01-14 17:20

    I will build on ws0205's answer:

    First, you indicate that you want your method "to be called with await". You achieve this by returning a Task.

    I also think that it's better to make the following adjustments to ws0205's answer:

    public Task<Result> SomeMethod() //no async, since we're not awaiting anything
    {
       var result = new TaskCompletionSource<Result>();
    
       library.WorkDone += (data) =>
                                    {
                                        result.TrySetResult(data); //just in case 
                                    };
       library.DoWork();
    
       return result.Task; //no need to await - we're returning a Task - let the caller await (or not)
    }
    
    0 讨论(0)
提交回复
热议问题