将事件转换为异步调用

我正在包装一个供我自己使用的库。 要获得某种财产,我需要等待一个事件。 我正在尝试将其包装成异步调用。

基本上,我想转

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或其他东西。

这就是TaskCompletionSource发挥作用的地方。 这里新的async关键字几乎没有空间。 例:

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

样本使用(花式异步)

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