Csharp/C#教程:将事件转换为异步调用分享


将事件转换为异步调用

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

基本上,我想转

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

样本使用(花式异步)

上述就是C#学习教程:将事件转换为异步调用分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注—计算机技术网(www.ctvol.com)!

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

本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。

ctvol管理联系方式QQ:251552304

本文章地址:https://www.ctvol.com/cdevelopment/1023873.html

(0)
上一篇 2022年1月8日
下一篇 2022年1月8日

精彩推荐