Sometimes, a controller action trigger a long running background process. For example, the user clicks a link in the page. Generate a word document in the background. Show the properties of the document in the subsequent page. Generation of word documents take anywhere between 3 seconds to 30 seconds. During this time, the user needs some feedback about the progress of the operation. This post shows how we can provide progress information to the user.

Consider an application with two pages. Index.cshtml and Generate.cshtml. The index page has a Generate link. When the user clicks the link, the Generate page is shown.

The Generate action is a long running operation that happens in the background. To execute long running operations from a controller, we derive the controller from AsyncController.

The three action methods in the above controller are Index, GenerateAsync and GetProgress. GenerateAsync action triggers the background operation. The background operation loops 100 times and sleeps for 300 ms in each iteration. At the end of each iteration, it reports percentage completed. The GetProgress action gets the completion status which is stored as a static variable. (Alternatively, store the variable in cache).

Add javascript to the Index page. It calls GetProgress action method at regular intervals and displays the progress.

Instead of displaying text, use a circular progress plugin to show the progress.

Showing the progress of long running controller actions
Tagged on: