Sometimes, the controller actions can trigger a long running background process. For example, when the user clicks a link in the page, a word document is generated in the background, and the properties of the word document is shown in the subsequent page. Generation of word documents can 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 you can provide progress information to the page which triggered the long running background process.

Consider a MVC application with two pages – Index.cshtml and Generate.cshtml. The Index.cshtml has a link – Generate. 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 MVC controller, we derive the controller from AsyncController. The following code snippet shows the HomeController with the background operations:

The three main action methods in the above controller are – Index(), GenerateAsync(), GetProgress(). Index() displays the Index page. GenerateAsync() 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 progress as a percentage. The GetProgress() action gets the reported progress which is stored as a static variable. The GetProgress() is triggered when the user clicks the link. The javascript in the Index page shows how the GetProgress() action method is called:

HTML:

On clicking the link, we call the setInterval() function that is triggered every second. In the recurring function, we call the action method – GetProgress(). We display the progress data in the page in the progress tag.

Showing the progress of long running controller actions
Tagged on:     

Leave a Reply

Your email address will not be published. Required fields are marked *