0
votes

I am using SignalR in loop like this:

int itemsCount = 100;

    for (int i = 0; i <= itemsCount; i++)
    {
        
        Thread.Sleep(100);

        SummaryHub.SendMessages("test", i.ToString());
     
    }

and client site is:

$(function () {

        var notifications = $.connection.SummaryHub;

        // Create a function that the hub can call to broadcast messages.
        notifications.client.broadcastMessage = function (name, message) {
            
           console.log(name);
           console.log(message);

          
        };

        // Start the connection.  
        $.connection.hub.start().done(function () {
     //  $.connection.hub.start({ waitForPageLoad: false }).done(function () {
            console.log("connection started")

        }).fail(function (e) {
            alert(e);
        });


    });

[HubName("SummaryHub")] public class SummaryHub : Hub {

[HubMethodName("sendMessages")]
public static void SendMessages(string name, string message)
{
           IHubContext context = GlobalHost.ConnectionManager.GetHubContext<SummaryHub>();
    context.Clients.All.broadcastMessage(name, message);
}

}

Problem is that client receive messages after loop is done, not during the loop. How can I fix that? Thanks

1
You show "SendMessages" in your loop but a different method on the client "broadcastMessage". Which is right and where is the code the for that? - Frank M
Add code above, thanks - user1663661
It seems your loop may be firing before the client is connected. You could try moving your loop into the hub method and call the hub method within the $.connection.hub.start().done(function () { } so it gets called after the connection is made. Or you could delay running that loop. - Frank M
No, I called loop after client is connected - user1663661

1 Answers

0
votes

I find out. It was ajax call with async:false and that was preventing sending messages to the client. Change async to true solved the problem