事件转成异步调用 [英] Turn event into a async call

查看:147
本文介绍了事件转成异步调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我包装我自己用的库。为了获得一定的属性,我需要等待一个事件。我想换行到异步调用。

I'm wrapping a library for my own use. To get a certain property I need to wait for an event. I'm trying to wrap that into an async call.

基本上,我想转

void Prepare()
{
    foo = new Foo();
    foo.Initialized += OnFooInit;
    foo.Start();
}
string Bar
{
    return foo.Bar;  // Only available after OnFooInit has been called.
}

进入这个

async string GetBarAsync()
{
    foo = new Foo();
    foo.Initialized += OnFooInit;
    foo.Start();
    // Wait for OnFooInit to be called and run, but don't know how
    return foo.Bar;
}

这怎么可能最好地完成?我可以只循环等待,但我试图找到一个更好的办法,如使用Monitor.Pulse()的AutoResetEvent或别的东西。

How could this best be accomplished? I could just loop and wait, but I'm trying to find a better way such as using Monitor.Pulse(), AutoResetEvent or something else.

推荐答案

多数民众赞成在TaskCompletionSource用武之地。很少有余地在这里新的异步关键字。例如:

Thats where TaskCompletionSource comes into play. There is little room for the new async keyword here. Example:

Task<string> GetBarAsync()
{
    TaskCompletionSource<string> resultCompletionSource = new TaskCompletionSource<string>();

    foo = new Foo();
    foo.Initialized += OnFooInit;
    foo.Initialized += delegate
    {
        resultCompletionSource.SetResult(foo.Bar);
    };
    foo.Start();

    return resultCompletionSource.Task;
}

使用示例(花式异步)

Sample use (with fancy async)

async void PrintBar()
{
    // we can use await here since bar returns a Task of string
    string bar = await GetBarAsync();

    Console.WriteLine(bar);
}

这篇关于事件转成异步调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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