Include an event in an asynchronous call

I wrap the library for my own use. To get a specific property, I need to wait for the event. I am trying to turn this into an asynchronous call.

Basically, I want to turn

void Prepare() { foo = new Foo(); foo.Initialized += OnFooInit; foo.Start(); } string Bar { return foo.Bar; // Only available after OnFooInit has been called. } 

In that

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

How could this be achieved? I could just loop and wait, but I'm trying to find a better way, for example, using Monitor.Pulse (), AutoResetEvent, or something else.

+8
c # asynchronous async-await
source share
1 answer

Thats where TaskCompletionSource comes into play. There is little room for the new async keyword. 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; } 

Using a sample (with fantastic asynchronous)

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

All Articles