Reputation: 608
My knowledge of how async/await
methods are run and on what thread is a little hazy. I would like to block a method until an event is fired. To do this I tried using the ManualResetEvent
however this blocks every call to the async method until the last waitHandle.Set( )
is called at which point all async
methods complete (or so it seems).
I need a way to block async
calls individually as I'm trying to convert the event based asynchronous approach to a Task
based async/await
one.
How can/should I go about it?
Update:
Based on the information provided by Stephen and Noseratio, I have now changed my asynchronous methods to something a long the lines of this:
public async Task<IEnumerable<CustomerNoteInfo>> LoadClientNotesAsync(int id)
{
return await _session.InvokeOperationAsync((client) =>
{
var tcs = new TaskCompletionSource<IEnumerable<CustomerNoteInfo>>( );
client.GetCustomerNotesCompleted += (sender, e) =>
{
if (e.Error != null) tcs.TrySetException(e.Error);
else tcs.TrySetResult(e.Result);
};
client.GetCustomerNotesAsync(id);
return tcs.Task;
}).Unwrap( );
}
I'm sure this is going to look ugly to everyone who has ever done any async/await Task based programming, but am I on the right track for this? It seems to have fixed the problem I was having with the manual reset event and I can now run this method multiple times asynchronously. :)
Upvotes: 0
Views: 909
Reputation: 456417
My knowledge of how async/await methods are run and on what thread is a little hazy.
I recommend you start with my async
intro, which covers the keywords and how they determine which thread to use.
I'm trying to convert the event based asynchronous approach to a Task based async/await one.
The MSDN documentation on this is quite good.
You do not need to block an async
method; just create a TAP (Task-based) wrapper for the EAP (method/event pair). Then you can just call your TAP method and await
the returned task.
Upvotes: 3