Pubnub执行同步请求

And*_*rei 6 .net c# asynchronous async-await pubnub

我有这个异步请求:

Pubnub pn = new Pubnub(publishKey, subscribeKey, secretKey, cipherKey, enableSSL);

pn.HereNow("testchannel", res => //doesn't return a Task
{ //response
}, err =>
{ //error response
});
Run Code Online (Sandbox Code Playgroud)

问题是我不知道如何同步运行它.请帮忙.

nos*_*tio 4

我不熟悉 pubnub,但你想要实现的目标应该像这样简单:

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();
Run Code Online (Sandbox Code Playgroud)

请注意,不建议同步执行异步操作。你应该看看 using async/await,在这种情况下你会这样做:

var result = await tcs.Task;
Run Code Online (Sandbox Code Playgroud)