C# Pubnub执行同步请求

C# Pubnub执行同步请求,c#,.net,asynchronous,async-await,pubnub,C#,.net,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 }); 问题是我不知道如何同步运行它。请帮助。我不熟悉pubnub,但您要实现的目标应该很简单: P

我有一个异步请求:

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

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

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

我不熟悉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();

我使用@Noseratio ideia解决了这个问题,并进行了简单的增强

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();
private任务GetOnlineUsersAsync()
{
var tcs=new TaskCompletionSource();
_pubnub.HereNow(主频道,
res=>tcs.SetResult(res),
err=>tcs.SetException(新异常(err.Message));
返回tcs.Task;
}
//使用
var users=await GetOnlineUsersAsync();

什么是Pubnub?那是你的。不是同步的还是异步的?@i3arnon我想同步执行这个请求。所以我需要等待回电。请发电子邮件给我们support@pubnub.com我们很乐意帮助你。太棒了。非常适合我。很好的解决方案,谢谢。最后一行应该是var res=tcs.Task.Result
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();