Hrishi
Hrishi

Reputation: 350

async await inside MVC controller

I have a controller action method that returns JSON result. In this controller action, i want to do asyc and await for a long running operation without waiting for the JSON result to return to the browser.

I have below sample code -

`public JsonResult GetAjaxResultContent(string id)
        {
            List<TreeViewItemModel> items = Test();
            //use the below long running method to do async and await operation.
            CallLongRunningMethod();

            //i want this to be returned below and not wait for long running operation to complete

            return Json(items, JsonRequestBehavior.AllowGet);
        }


private static async void CallLongRunningMethod()
        {

            string result = await LongRunningMethodAsync("World");

        }

        private static Task<string> LongRunningMethodAsync(string message)
        {
            return Task.Run<string>(() => LongRunningMethod(message));
        }

        private static string LongRunningMethod(string message)
        {
            for (long i = 1; i < 10000000000; i++)
            {

            }
            return "Hello " + message;
        }

`

However, the controller action waits untill it finishes the long running method and then returns the json result.

Upvotes: 1

Views: 2664

Answers (2)

Stephen Cleary
Stephen Cleary

Reputation: 456322

In this controller action, i want to do asyc and await for a long running operation without waiting for the JSON result to return to the browser.

That's not how async works. As I describe on my blog, async does not change the HTTP protocol.

If you want a "background" or "fire-and-forget" task in ASP.NET, then the proper, reliable way to do it is:

  1. Post the work to a reliable queue. E.g., Azure queue or MSMQ.
  2. Have an independent process that retrieves work from the queue and executes it. E.g., Azure webrole, Azure web worker, or Win32 service.
  3. Notify the browser of the results. E.g., SignalR or email.

Starting a separate thread or task in ASP.NET is extremely dangerous. However, if you are willing to live dangerously, I have a library you can use to register "fire and forget" tasks with the ASP.NET runtime.

Upvotes: 2

Nisd
Nisd

Reputation: 1133

You could do like this:

new System.Threading.Thread(() => CallLongRunningMethod()).Start();

And start your method in a new thread.

But starting new threads on a web server is not recommend, because the application pool could shutdown at anytime without you knowing, and put your application in a invalid state.

Upvotes: 0

Related Questions