Pubnub executes a synchronization request

I have an 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 do not know how to run it synchronously. Please, help.

+6
source share
2 answers

I am not familiar with pubnub, but what you are 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(); 

Please note that running an asynchronous file synchronously is not recommended. You should look at using async/await , in which case you would do:

 var result = await tcs.Task; 
+4
source

I solved this problem with @Noseratio ideology with a simple improvement.

 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(); 
+1
source

Source: https://habr.com/ru/post/982399/


All Articles