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

≯℡__Kan透↙ 提交于 2019-12-30 10:32: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 calls this library, but instead of maintaining the same pattern I would like my method to be async so it can be called with await.

In essence, what I am trying to do is:

public async Task<Result> SomeMethod()
{
    var result = new Task<Result>();

    library.WorkDone += (data) =>
    {
        result.Result = data;
    }
    library.DoWork();

    return await result;
}

(not working because Result is readonly)

Can this be done?


回答1:


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)
}



回答2:


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;
}


来源:https://stackoverflow.com/questions/16206820/how-to-use-async-await-with-a-library-that-uses-an-event-based-asynchronous-patt

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!