3
votes

In one of my WCF-Services (stateless), I want to send a message via SignalR. Because the service is stateless, and the hub is on another machine, I connect to SignalR, send the message, and disconnect.

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

From time to time, there are InvalidOperationExceptions (Connection was disconnected before invocation result was received).

I understand from this post (C# SignalR Exception - Connection started reconnecting before invocation result was received) that .Wait is not a good idea. But I think I need to wait for Connect and SendMessage to complete, before disconnect.

So, what else can I do?

Best regards, Stefan

2

2 Answers

2
votes

The error makes sense because the code is synchronous. Thus Disconnect may be called before invocation result is received.

What about...

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

That way you are making sure proxy.Disconnect() will not be called until message is sent.

0
votes

It might be because you return an entity framework object.

When you do, make sure to Detatch them from the Context first, like:

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;
    }
}