【问题标题】:SignalR: Connection was disconnected before invocation result was receivedSignalR:在收到调用结果之前连接已断开
【发布时间】:2016-11-07 03:20:45
【问题描述】:

在我的一个 WCF 服务(无状态)中,我想通过 SignalR 发送一条消息。因为服务是无状态的,并且集线器在另一台机器上,所以我连接到 SignalR,发送消息,然后断开连接。

proxy.Connect().Wait();
proxy.SendMessageToUsers(receiverUserNames, message).Wait();
proxy.Disconnect();

有时会出现InvalidOperationExceptions(在收到调用结果之前连接已断开)。

我从这篇文章 (C# SignalR Exception - Connection started reconnecting before invocation result was received) 了解到 .Wait 不是一个好主意。但我想我需要等待 Connect 和 SendMessage 完成,然后再断开连接。

那么,我还能做什么?

最好的问候, 斯蒂芬

【问题讨论】:

    标签: c# signalr


    【解决方案1】:

    错误是有道理的,因为代码是同步的。因此Disconnect可能会在收到调用结果之前被调用。

    怎么样……

    Task.Factory.StartNew(async() => {
        await proxy.Connect();
        await proxy.SendMessageToUsers(receiverUserNames, message);
        await proxy.Disconnect();
    });
    

    这样可以确保在发送消息之前不会调用proxy.Disconnect()

    【讨论】:

    • 这对我来说没有任何意义。是 proxy.SendMessageToUsers(receiverUserNames, message).Wait();与等待代理不同。SendMessageToUsers(receiverUserNames, message); ?
    • 好吧,我发现自己的情况是 Wait() 不起作用,但 await 起作用。试一试需要2秒
    【解决方案2】:

    这可能是因为您返回了一个实体框架对象。

    当你这样做时,请确保首先从上下文中Detatch 他们,例如:

    public List<Models.EF.Inventarisatie.ScannerAanmelding> GetRecentSessions()
    {
        using (var db = new Models.EF.Inventarisatie.inventarisatieEntities())
        {
            var result = db.ScannerAanmelding
                .Where(sa => sa.FK_Inventarisatie_ID == MvcApplication.Status.Record.PK_Inventarisatie_ID)
                .GroupBy(sa => sa.FK_Scanner_ID)
                .Select(sa => sa.OrderByDescending(x => x.Moment).FirstOrDefault())
                .ToList();
            // make sure to disconnect entities before returning the results, otherwise, it will throw a 'Connection was disconnected before invocation result was received' error.
            result.ForEach((sa) => db.Entry(sa).State = System.Data.Entity.EntityState.Detached);
            return result;
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2014-04-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-05-01
      • 2012-04-20
      • 2021-12-05
      • 2012-04-05
      相关资源
      最近更新 更多