I have an application where I need the user to upload a photo. After the photo is uploaded to the server, which shouldn't take very long, the user should get back a response that's a regular HTML page saying "thanks...bla bla bla..."
Now, after the the response is sent back to the client and he goes on his merry way, I want the server to continue to work on this photo. It needs to do something that's heavy and would take a long time. But this is okay because the user isn't waiting for anything. He's probably in a different page.
So my question is, how do I do this with ASP.NET.
The application I'm writing is in ASP.NET MVC so I'm imagining something like
//save the photo on the server
//and send viewdata saying "thanks..."
return View();
//keep doing heavy processing on the photo
But I guess this isn't really how it's done. Also, since sometimes I work with ASP.NET WebForms, how is this done with WebForms as well.
Thank you!
We do this for a lightweight logging situation:
Action<object> d = delegate(object val)
{
// in this anonymous delegate, write code that you want to run
ProcessDataAndLog();
};
d.BeginInvoke(null, null, null); // this spins off the method asynchronously.
It's by no means robust. If you need a guarantee of being processed you should consider a message queue. That way you can also offload processing to a separate machine and not bog down your web server.
EDIT:
The following also works, and is perhaps a little more obvious to your fellow coder. It's essentially the same, but apparently faster and you don't need to worry about calling EndInvoke().
System.Threading.ThreadPool.QueueUserWorkItem(
delegate(object state)
{
// in this anonymous delegate, write code that you want to run
ProcessDataAndLog();
});
Further Reading: The Thread Pool and Asynchronous Methods and Asynchronous delegate vs thread pool & thread and Does not calling EndInvoke really cause a memory leak ?
It seems to me like you need to spin off another process to do what you need to do. You might even want to build a windows service to handle the processing of the image. It could be an app that sits around waiting for a file to appear somewhere, and when it does it can go to work leaving the asp.net thread to go about its business.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With