SoFunction
Updated on 2025-03-04

.Net MVC implements long polling

What is long polling?

Long polling is a method of implementing the "server push" technology. It can transmit changes that occur on the server to the client in real time without the need for the client to refresh or send requests frequently.

Long polling principle?

The client sends an Ajax request to the server. After the server receives the request, it keeps the connection without returning a message. It does not return the response information until the relevant processing is completed and the connection is closed. After the client receives the response information, it performs the relevant processing. After the processing is completed, it wants the server to send a new request.

Application scenarios for long polling?

Long polling is often used in scenarios where changes on the server side are sent to the client in real time, such as Web time communication, monitoring, real-time quotation systems, etc.

What are the advantages and disadvantages of long polling?

Advantages: When there is no message, you will not send requests to the server frequently.

Disadvantages: Keeping the server connected is more resource-intensive

accomplish:

Front Desk Code:

In the callback, we call the function again so that after each request is closed, we start the next request.

<div ></div>
<script type="text/javascript">
  $(function () {
    function longPolling() {
      $.getJSON("/DateTime/GetTime", function (json) {
        $("#container").append( + "<br/>");
        longPolling();
      });
    };
    longPolling();
  });
</script>

Background code:

Our background controller needs to use asynchronously and inherit the AsyncController base class

public class DateTimeController : AsyncController
  {
    public void GetTimeAsync()
    {
      //Timer, trigger an Elapsed event in 5 seconds       timer = new (5000);
      //Tell .NET to perform an asynchronous operation next      ();
      //Subscribe to the Elapsed event of the timer       += (sender, e) =&gt;
      { //Save the parameters to be passed to GetTimeCompleted        ["nowdate"] = ;
        //Tell the asynchronous operation has been completed and make a call to the GetTimeCompleted method        ();
      };
      //Start the timer      ();
    }
    public ActionResult GetTimeCompleted(DateTime nowdate)
    {
      return Json(new { date = ("HH:mm:ss") + " Welecom " }, );
    }
  }

The above is all the content of this article. I hope it will be helpful to everyone's study and I hope everyone will support me more.