如何将 async/await 与使用基于事件的异步模式的库一起使用? [英] How to use async/await with a library that uses an event-based asynchronous pattern?

查看:38
本文介绍了如何将 async/await 与使用基于事件的异步模式的库一起使用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用的库有一个名为 DoWork(...) 的异步方法,该方法会在操作完成时引发 WorkDone 事件.

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

我想编写一个调用这个库的方法,但我希望我的方法不是保持相同的模式,而是 async 这样它就可以用 await 调用>.

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.

本质上,我想做的是:

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)

这能做到吗?

推荐答案

我将以 ws0205 的答案为基础:

I will build on ws0205's answer:

首先,您表明您希望您的方法await"调用.您可以通过返回 Task 来实现这一点.

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

我也觉得对ws0205的回答做如下调整比较好:

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

这篇关于如何将 async/await 与使用基于事件的异步模式的库一起使用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆