Reputation: 739
To get data from a server asynchronously I use getData.BeginInvoke(callback, null)
, where getData
is the method that gets the data. The callback
does some work & notification on the retrieved data.
In a calling method, I have read the good practice is to use a WaitHandle
to wait for the method to be completed. My question is : Does the WaitHandle
also waits for the callback to complete ? If not, how to do so ?
Code :
Func<Data> getData = () =>
{
//...
};
AsyncCallback callback = (IAsyncResult ar) =>
{
//...
};
IAsyncResult result = getData.BeginInvoke(callback, null);
result.AsyncWaitHandle.WaitOne();
Note1 : I have to use framework 3.5, so I can not use async
& await
Note2 : I don't think this question is a duplicate of this post.
Upvotes: 1
Views: 689
Reputation: 173
You are right, WaitOne means that the target of BeginInvoke has completed but it does not guarantee the completion of the callback. In this case you have to use ManualResetEvent
in order to handle it manually yourself:
Func<Data> getData = () =>
{
//...
};
AsyncCallback callback = (IAsyncResult ar) =>
{
// do your thing...
getData.EndInvoke(ar);
waiter.Set();
};
ManualResetEvent waiter;
void DoWork()
{
waiter = new ManualResetEvent(false);
IAsyncResult result = getData.BeginInvoke(callback, null);
waiter.WaitOne();
//Callback has finished
}
Upvotes: 3