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.
Basically, I want to turn
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);
}