Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Starting a background task ASP.NET MVC 4.5

I implemented a simple pdf uploader in ASP.NET MVC and I need to process the uploaded document. Because the processing can take a while, I want this to be done in background. The workflow is something like this: I want the user to upload the document, and when the document is saved in the database he should be able to do other stuff on the web site, including upload of new documents. User should not know anything about the processing in the background.

My implementation looks something like this:

[HttpPost]
public async virtual Task<ActionResult> Confirm(string author, string title)
{
    //...
    previousDocumentIsProcessing = true; 
    await InvokeDocumentProcessor(_document.Path, _document.DocumentID);
    previousDocumentIsProcessing = false; 

    return View("Success");
}

The problem is that the "Success" view is being displayed after the processing is done. Users can click around and do other stuff since the operation is async, but what I want to create a background process, start it and display the "Success" view right away. The user should not be bothered by the processing.

How can I achieve this? I have tried with a background worker but it did not work (I got the error saying that the async process can not be started at that point).

like image 425
mobearette Avatar asked Jan 11 '14 12:01

mobearette


1 Answers

User should not know anything about the processing in the background.

Are you sure? What if there's an error during processing? How does the user know when the processing is done?

How can I achieve this?

As I explain on my blog, async does not change the HTTP protocol.

The proper solution is to save the uploaded file somewhere (e.g., Azure blob storage), insert a message into a reliable message queue (e.g., Azure queue storage), and have a completely independent back-end that does the processing (e.g., Azure worker role).

If you want an improper (in-memory) solution, I have another blog post describing that approach.

like image 73
Stephen Cleary Avatar answered Sep 28 '22 03:09

Stephen Cleary