Reputation: 711
I am working with a library for which I do not have the source, and as such I can't decorate it with the async keyword and do things like await
a Task
(at least I don't know how to do that). It exposes a method which returns an object (I'll call it "answer") and takes an integer, and a parameter of type Action
where I retrieve that answer. How can I wait for answer to get populated before my code continues?
Object answer = null;
remoteLibrary.remoteMethod(42, x =>
{
answer = x.Value; //This might take a few seconds
});
//I want to do something here with "answer" AFTER it has been populated
Upvotes: 1
Views: 48
Reputation: 116676
You need a synchronization construct. And since this can take a few seconds it would be a waste to use a synchronous (blocking) one so I suggest an asynchronous one like TaskCompletionSource
:
var tcs = new TaskCompletionSource<object>();
remoteLibrary.remoteMethod(42, x =>
{
tcs.SetResult(x.Value);
});
var answer = await tcs.Task;
// use answer
The TaskCompletionSource
exposes a task that you can await
that wouldn't complete until you call SetResult
(or SetCanceled
, SetException
). When it completes you get the result you set in SetResult
so you don't need the dummy variable anymore.
Upvotes: 2