Context
I have this function which synchronize a list of sites between a table and several remote IIS:
namespace Dashboard.Controllers
{
public class SiteController : Controller
{
public ActionResult Synchronize()
{
SiteModel.synchronizeDBWithIIS();
return Content("Cool.");
}
}
}
I want to call this function asynchronously when the dashboard is starting and running.
Questions
-
You advise me to do a
$.get()(jQuery) or to useAsyncResult(ASP.NET)? -
May be use
Application_start()inGlobal.asax? -
Furthermore, can I improve this controller for synchronization go faster?
None of the above. This is something that you shouldn’t be doing in an ASP.NET application at all. You may read the following article about the dangers of this: http://haacked.com/archive/2011/10/16/the-dangers-of-implementing-recurring-background-tasks-in-asp-net.aspx
This is something that should be done in a separate application. You could use the Windows task scheduler for example to run this application at regular intervals and it will take care of doing this lengthy operation.
There’s nothing worse in an ASP.NET application than blocking a worker thread for a long time. The only possible acceptable solution to implement this in an ASP.NET application is to use I/O Completion Ports. Then you could use an AsyncController. But from what I can see your
SiteModel.synchronizeDBWithIIS();is a blocking method so it cannot be done.But if your
SiteModeloffered an asynchronous API to perform an I/O intensive task (not CPU intensive) here’s how it could be implemented:Once you have done that whether you will invoke the Synchronize action using an AJAX call or a normal call it doesn’t really matter. What matters is that this action is now asynchronous and doesn’t block a worker thread. It delegates this to the underlying API which at the moment to perform lengthy I/O operations uses the BeginXXX, EndXXX methods on the Streams, Sockets, Database Connections, … It is important to understand that if your API doesn’t already implement this, you cannot just wrap a synchronous method in a new thread or an async delegate and execute it there. I mean you can, but you gain strictly nothing from doing that.
Remark: don’t be fooled into thinking that this will make your operation faster. There’s no miracles for that. The operation will take exactly the same time as before. It’s just that during its execution you won’t be jeopardizing ASP.NET worker threads and your other requests will be executed faster.