How do I start a task in mvc and get notified when the task is complete?

I've never tried running asynchronous tasks in mvc, so I'm not sure which direction to go in.

I have a class that generates an excel file from a large amount of data, which can take a while. I want this to be when the user clicks on the link get a message saying "you will be notified of completion" and the task will start, then they can continue with the web app and they get a screen notification, maybe via ajax ... Several tasks can be performed at the same time. It would be nice if I could see the task is still running.

These tasks are never scheduled, always "on demand"

Which method is most suitable for this? I've seen system.threading, signalr , quartz.net , etc. there, but some might be overkill.

thank,

Sam

+3


source to share


2 answers


On the client side, you will need to create javascript polling code.
Something like that:

(function poll(){
   setTimeout(function(){
      $.ajax({ url: "server/checkStatus", success: function(data){
        // check notification data and react accordingly
      }, dataType: "json"});
  }, 30000);
})();

      

See also:

On the server side, instantiate an object like this (simplified):



class MyTasks
{
   Dictionary<int, Task> tasks;

   public bool AllTasksDone {get;}
   public bool GetNumberOfRunnigTasksForUser(int userId){}

   public void AddTask(int userId, Task task){}
}

      

You can put this in Application

or in Session

(one instance per user session). And use it to respond to survey requests.

Tasks can be easily created Task.StartNew(MethodName)

orTask.StartNew(()=>{your code})

Just to mention - there is another way to do this - WebSockets. But this is too heavy a weapon. You probably don't want this.

+4


source


2 possibilities come to mind: AJAX or SignalR. The first is the naive approach. You start a task, and then at regular intervals you will use an AJAX call to check if that task has completed. The downside is that you will be sending many requests to your server.



The second approach involves using SignalR, which in modern browsers can use WebSockets and Push Notifications to clients. Unlike the AJAX polling method, with SignalR it is a server that can inform clients that a task has progressed or completed on the server. It is much optimized for such scenarios. I personally would recommend that you use SignalR for this task.

+3


source







All Articles