Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pubnub perform sync request

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.

like image 217
Andrei Avatar asked Feb 12 '15 20:02

Andrei


2 Answers

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;
like image 98
noseratio Avatar answered Nov 20 '22 04:11

noseratio


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();
like image 40
jzeferino Avatar answered Nov 20 '22 05:11

jzeferino