Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Delay Calling a function After full page loaded on aspx with c#

Below is my simple source code, I'm just trying to call that function after page load, but what is happening right now is: it calls that function before page load. Page loads for 5 seconds and, after that, it displays label execution.

protected void Page_Load(object sender, EventArgs e)
{
   display();
}

void display()
{
    Thread.Sleep(5000);
    Label3.Text = "done";
}
like image 667
Jitender Avatar asked Nov 05 '18 06:11

Jitender


1 Answers

You should read this document about ASP.NET Page Life Cycle. It actually says what you are trying to do is not possible.

Every code you write in the server side is going to run before the browser renders the page. That means you can not call a function after the browser renders the page, unless you use other approach.

The simplest way you can achieve this is using Javascript and an Ajax call or by using a Timer, which opens a new thread different from the main execution thread. Although, I do not recommend open new threads, because you will lose the control over the execution flow and in a webpage you could end having hundreds of open threads.

like image 197
Daniel Marín Avatar answered Sep 19 '22 08:09

Daniel Marín