In my C# ASP.NET project I’ve got a background thread that does some processing. I want to display to the user when the background process starts and when it ends. To that end, in the background code I’ve got:
public static void RefreshNavigationElements()
{
TimeInfoEventArgs timeInformation = new TimeInfoEventArgs("WPALoading has started");
WorkProductAgreements.OnSecondChange(timeInformation);
WPA_Supers.Clear();
PopulateWPAs();
timeInformation.myMessage = "WPALoading has ended";
WorkProductAgreements.OnSecondChange(timeInformation);
}
The code that’s listening to the event:
public void TimeHasChanged(TimeInfoEventArgs ti)
{
Label11.Text = ti.myMessage;
System.Diagnostics.Debug.WriteLine(ti.myMessage);
}
Stepping through things in the debugger shows that the TimeHasChanged function gets called at the appropriate times with the correct text inside of ti. The Debug.WriteLine command outputs the right message. But the Label11 text doesn’t change on the page.
In my not-very-deep understanding of things, I think I just need to trigger a refresh of the page, or something similar, but I can’t, for the life of me, figure out how to do that.
I’ve tried placing the Label inside an UpdatePanel. I’ve tried creating a new label each time TimeHasChanged gets called. But none of my attempts seem to make any difference. Any help would be greatly appreciated.
In ASP.NET, when a browser request a page, the server starts a thread to render the page and send it back to the browser. Once the page is rendered, the thread is finished, and all related background workers are also finished. The page is sent back to the browser as is at this point. So, unless you explicitly wait until the background worker finishes, it will never finish and update the page content.
You can use some of the techniques here:
But, if your background worker takes quite a long time to execute, as the page won’t be sent to the browser until the thread finish, you can get timeouts or unresponsive pages in your browser.
To avoid this you can use AJAX and web services: expose the functionality of the background worker in a web service method, and use AJAX to execute this method. Once this method has finished, you can update the labels directly in the browser. While this happens, the browser is still responsive.
for this you can use jQuery and ASP.NEt web service, like explained here.
Finally, you should never run a really long process in ASP.NET: the server recycles (restarts) the application from time to time, and this can stop the execution of you web service method abruptly.