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.

Andrei
  • 42,814
  • 35
  • 154
  • 218

2 Answers2

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;
noseratio
  • 59,932
  • 34
  • 208
  • 486
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();
jzeferino
  • 7,700
  • 1
  • 39
  • 59