Need an ASP.NET MVC long running process with user feedback

前端 未结 3 1336
悲&欢浪女
悲&欢浪女 2020-12-02 05:19

I\'ve been trying to create a controller in my project for delivering what could turn out to be quite complex reports. As a result they can take a relatively long time and a

3条回答
  •  盖世英雄少女心
    2020-12-02 05:45

    4.5 years after this question has been answered, and we have a library that can make this task much easier: SignalR. No need to use shared state (which is bad because it can lead to unexpected results), just use the HubContext class to connect to a Hub that sends messages to the client.

    First, we set up a SignalR connection like usual (see e.g. here), except that we don't need any server-side method on our Hub. Then we make an AJAX call to our Endpoint/Controller/whatever and pass the connection ID, which we get as usual:var connectionId = $.connection.hub.id;. On the server side of things, you can start your process on a different thread and retutn 200 OK to the client. The process will know the connectionId so that it can send messages back to the client, like this:

    GlobalHost.ConnectionManager.GetHubContext()
                                  .Clients.Client(connectionId)
                                  .log(message);
    

    Here, log is a client-side method that you want to call from the server, hence it should be defined like you usually do with SignalR:

    $.connection.logHub.client.log = function(message){...};
    

    More details in my blog post here

提交回复
热议问题