MVC futures async operations
I could not find a way of displaying a please wait page while doing an async operation;
What I am trying to implement is a search page which displays 'please wait' animation while the search operation is being done by an async thread.
I am pasting the simple test code I implemented below. The initial "Searching" view is never displayed even though debugger goes through that line. I only see the final 'Results' view after the operation is complete;
public class HomeController : AsyncController
{
public ActionResult Search()
{
// Add an asynchronous operation
AsyncManager.OutstandingOperations.Increment();
ThreadPool.QueueUserWorkItem(o =>
{
Thread.S开发者_StackOverflowleep(5000);
AsyncManager.OutstandingOperations.Decrement();
}, null);
return View("Searching");
}
public ActionResult SearchCompleted() {
return View("Results");
}
}
Actually you don't need an asynchronous call as you want to wait until the end of the process. Use asynchronous methods when you don't want to wait for the result.
All you need is a hidden div on your page with the text "Searching".
- Mark Search as [POST] action and post your form to this action
- Use javascript to show the "Searching" div when the page is posted.
$("#searching").show();
$("form").submit();
When the process ends go to results view.
That's it.
If you still want to call an async action see: http://msdn.microsoft.com/en-us/library/ee728598(VS.100).aspx#performing_multiple_operations_in_parallel
This is a Web Application, you cant do that from server to client. You will must implement something with ajax. I will give you the basis to do it, if you want a code example let me know.
1) The bottom "Search" must call a js function that shows the "Please Wait" message.
2) The same js function must call the server method that do the search (with ajax). Here I recomend to use JQuery, it has a method called ajax that is very simple to use.
3) Do the search in the server method and return the result in a html or xml or json format.
4) On the js callback method, hide the "Please wait" message and show the search result.
Async methods run on the server, not the client. You would use an async controller if, for example, you want to call multiple web services to get data for your page. You can queue requests to all of them, they will run in parallel and upon completion, asp.net will bring them all together to finish assembling your page.
In your scenario you are already making a partial request from a completed page and don't really need an async controller. Unless you find through testing that your requests are queueing, I would avoid this added complexity.
精彩评论