I have this asynchronous request:
Pubnub pn = new Pubnub(publishKey, subscribeKey, secretKey, cipherKey, enableSSL);
pn.HereNow("testchannel", res => //doesn't return a Task
{ //response
}, err =>
{ //error response
});
The problem is that I don't know how to run it synchronously. Please help.
I'm not familiar with pubnub, but what you're trying to achieve should be as simple as this:
Pubnub pn = new Pubnub(publishKey, subscribeKey, secretKey, cipherKey, enableSSL);
var tcs = new TaskCompletionSource<PubnubResult>();
pn.HereNow("testchannel", res => //doesn't return a Task
{ //response
tcs.SetResult(res);
}, err =>
{ //error response
tcs.SetException(err);
});
// blocking wait here for the result or an error
var res = tcs.Task.Result;
// or: var res = tcs.Task.GetAwaiter().GetResult();
Note that doing asynchronous stuff synchronously is not recommend. You should look at using async/await
, in which case you'd do:
var result = await tcs.Task;
I solved this issue using the @Noseratio ideia with a simple enhancement.
private Task<string> GetOnlineUsersAsync()
{
var tcs = new TaskCompletionSource<string>();
_pubnub.HereNow<string>(MainChannel,
res => tcs.SetResult(res),
err => tcs.SetException(new Exception(err.Message)));
return tcs.Task;
}
// using
var users = await GetOnlineUsersAsync();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With