我是一名有用的助手,可以为您进行翻译。以下是需要翻译的内容:
我正在为自己使用封装一个库。为了获取某个属性,我需要等待一个事件。我试图将其包装成异步调用。
基本上,我想要转换:
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或其他方法。
foo
调用其 Initialized 事件之前,它将从作用域中消失。你可能没问题,但有一个危险,即foo
可能已经被垃圾回收了。为了保持它的存活,你可以将它作为状态传递到 TaskCompletionSource 构造函数中。 - dumbledad