How to properly execute the Async method in ASP.net MVC?

How to execute an asynchronous method from a controller method and return HttpStatusCodeResult (200) without an async delegate that terminates it prematurely?

I am working on an asp.net application and one of my actions my home controller takes a lot of time (10-30 seconds). I want to return HttpStatusCodeResult (200) and continue to execute my function. The functional does not need to return anything, but still this is not really a case of fire and to forget, since I immediately return the response to the server using HttpStatusCodeResult.

I tried using delegates, but it seems that when I return the status code from the action, the delegate will stop executing. Another option is to create a Windows service, but it would be like using a bazooka to kill a fly. I receive very few requests, so resources and performance are not a problem in my case. I heard that ThreadPool.QueueUserWorkItemthis is an option, but the most suitable for my case?

+5
source share
1 answer

Create a static class that manages this long-running operation. This class will be responsible for creating threads for the task, and also provides the ability to check the status of any ongoing operations (that is, if it is still running or completed, and if so, what is the result).

MVC- .

- :

public ActionResult GetSomething(String id) {
    TaskResult result = TaskClass.GetStatus( id );
    if( result == null ) { // the task has not been run, so start it up
        TaskClass.StartNew( id );
        return new View("PleaseWait");
    } else if( !result.IsFinished ) {
        return new View("PleaseWait");
    } else {
        return View("Results", result);
    }
}

public static class TaskClass {
     private static Dictionary<String,TaskResult> _tasks;
     public static TaskResult GetStatus(String id) {
         // TODO: Make this code thread-safe
         if( _tasks.ContainsKey(id) ) return _tasks[id];
         return null;
     }
     public static void Start(String id) {
         _tasks.Add( id, new TaskResult("Working") );
         Thread thread = new Thread( SomeExpensiveOperation );
         thread.Start( id );
     }
}

SomeExpensiveOperation , TaskResult .

+1

All Articles