SignalR:在收到调用结果之前断开连接

时间:2016-07-05 10:17:57

标签: c# signalr

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

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

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

我从这篇文章(C# SignalR Exception - Connection started reconnecting before invocation result was received)中了解到。等等不是一个好主意。但我认为在断开连接之前我需要等待Connect和SendMessage完成。

那么,我还能做些什么呢?

祝你好运, 斯蒂芬

2 个答案:

答案 0 :(得分:0)

错误有意义,因为代码是同步的。因此,在收到调用结果之前,可以调用Disconnect

怎么样......

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

通过这种方式,您确保在发送邮件之前不会调用proxy.Disconnect()

答案 1 :(得分:0)

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

这样做时,请确保首先从上下文中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;
    }
}
相关问题