I have an API whose interface looks like this:
void SendRequest(Guid id, IRequest request);
event EventHandler<ResponseEventArgs> ResponseReceived;
What’s the best way of implementing this method?
Task<T> GetResponse(IRequest request) where T: IRequest
Note that multiple requests may overlap each other, so when a response comes back I need to look up the parent request. I have a feeling TaskCompletionSource may be of use, but can’t quite piece it together.
EDIT:
If you want to do this without blocking a thread, you can do something like this using
TaskCompletionSource<T>:Original Answer:
I think you want something like the following, which uses a
ManualResetEventto block the thread until the event is raised by the API:For a cleaner way of doing this, look into Reactive Extensions.