Long polling Stop other request for 1 or 2 minutes

前端 未结 4 1886
你的背包
你的背包 2021-01-15 04:03

During create a chat system , I use a long life request to get message , and use a jquery request to send message like this :

*Send: *

$(\"         


        
4条回答
  •  鱼传尺愫
    2021-01-15 04:20

    The problem is GetRecords may never return. Which, unless you are using something like WebSockets is an issue. It means the connection will never complete (until it times out) and you will more than likely not receive any data from it.

    What you should do is let GetRecords return straight away, and then poll in your jQuery for new records every X seconds.

    You could also try adding a Sleep in the while loop (as well as a maximum loop limit) to allow other threads to work in the system and to prevent an infinite loop. i.e.

    int maxLoops = 50;
    int loopNum = 0;
    while (loopNum < maxLoops)
    {
            var list = db.Commets.Where(rec => rec.Id > Id).Select(rec => new { Id = rec.Id, Str = rec.Str }).ToList();
    
            if (list.Count > 0)
                return list;
    
            Thread.Sleep(250); //Wait 1/4 of a second
            loopNum++;
    }
    

提交回复
热议问题