Joh*_*lip 8 c# asynchronous async-await
我正在包装一个供我自己使用的库.要获得某个属性,我需要等待一个事件.我正在尝试将其包装成异步调用.
基本上,我想转
void Prepare()
{
foo = new Foo();
foo.Initialized += OnFooInit;
foo.Start();
}
string Bar
{
return foo.Bar; // Only available after OnFooInit has been called.
}
Run Code Online (Sandbox Code Playgroud)
进入这个
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;
}
Run Code Online (Sandbox Code Playgroud)
怎么能最好地完成?我可以循环并等待,但我正在尝试找到更好的方法,如使用Monitor.Pulse(),AutoResetEvent或其他东西.
Pol*_*ity 25
这就是TaskCompletionSource发挥作用的地方.这里新的async关键字几乎没有空间.例:
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;
}
Run Code Online (Sandbox Code Playgroud)
样本使用(花式异步)
async void PrintBar()
{
// we can use await here since bar returns a Task of string
string bar = await GetBarAsync();
Console.WriteLine(bar);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3160 次 |
| 最近记录: |