Pubnub perform sync request
Asked Answered
E

2

6

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.

Exult answered 12/2, 2015 at 20:13 Comment(6)
What's Pubnub? Is that yours.Collett
Nope pubnub.comExult
synchronously or asynchronously?Collett
@Collett I'd like to perform this request synchronously. So I need to wait for a callback somehow.Exult
Please shoot us an email at [email protected] and we'd be happy to assist you.Judicious
@AndreiM did you contact pubnub via email for this question?Oof
B
4

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;
Byronbyrum answered 13/2, 2015 at 0:43 Comment(2)
Awesome. Works perfectly for me.Exult
Good solution, thanks. Last line should be var res = tcs.Task.ResultGrounder
O
1

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();
Oof answered 7/4, 2016 at 13:30 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.