Reputation: 350
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
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:
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
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