【问题标题】:Pubnub perform sync requestPubnub 执行同步请求
【发布时间】:2015-02-12 20:13:52
【问题描述】:

我有这个异步请求:

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

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

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

【问题讨论】:

  • 什么是 Pubnub?那是你的吗?
  • 同步还是异步?
  • @i3arnon 我想同步执行这个请求。所以我需要以某种方式等待回调。
  • 请发送电子邮件至 support@pubnub.com,我们很乐意为您提供帮助。

标签: c# .net asynchronous async-await pubnub


【解决方案1】:

我对 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();

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

var result = await tcs.Task;

【讨论】:

  • 太棒了。非常适合我。
  • 很好的解决方案,谢谢。最后一行应该是 var res = tcs.Task.Result
【解决方案2】:

我使用@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();

【讨论】:

    猜你喜欢
    • 2011-10-04
    • 2015-02-10
    • 1970-01-01
    • 2020-03-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-27
    • 1970-01-01
    相关资源
    最近更新 更多