Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

asp.net update UI using multi-thread

I have an ASP.NET website containing the following

<asp:UpdatePanel ID="UpdatePanel1" runat="server" >
     <ContentTemplate>
          <asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>                
     </ContentTemplate>            
</asp:UpdatePanel>

I have created a thread function. And during the execution of this function I would like to update some controls on the user interface.

protected void Page_Load(object sender, EventArgs e)
{
    new Thread(new ThreadStart(Serialize_Click)).Start();
}
protected void Serialize_Click()
{
    for (int i = 1; i < 10; i++)
    {
        Label1.Text = Convert.ToString(i);
        UpdatePanel1.Update();
        System.Threading.Thread.Sleep(1000);
    }
}

How could I update a web-control during a thread-execution? do I need to force the "UpdatePanel1" to post-back? how?

like image 829
ala Avatar asked May 13 '09 13:05

ala


2 Answers

You'll need to use a client-side timer (or some other method) to have the browser ask the server for the update, such as this simplified example:

<asp:UpdatePanel ID="up" runat="server">        
    <ContentTemplate>
        <asp:Timer ID="Timer1" runat="server" Interval="1000" OnTick="timer_Ticked" />
        <asp:Label ID="Label1" runat="server" Text="1" />
    </ContentTemplate>
</asp:UpdatePanel>

Then in your codebehind:

protected void timer_Ticked(object sender, EventArgs e)
{
    Label1.Text = (int.Parse(Label1.Text) + 1).ToString();
}

If you have a background process that is updating some state, you will either need to store the shared state in the session, http cache, or a database. Note that the cache can expire due to many factors, and background threads can be killed any any tie if IIS recycles the application pool.

like image 163
Jason Avatar answered Oct 21 '22 20:10

Jason


This won't do what you think it will.

It would make more sense to use a js timer on the front end to call a webmethod that updates the page.

Remember that to the server, once the page is rendered to you, it does not exist anymore until called again. The web is a stateless medium. Postback and viewstate make it feel like it's not, but it really is.

As such, you won't be able to call the client from the server, which is what you are attempting to do.

like image 42
Chad Ruppert Avatar answered Oct 21 '22 21:10

Chad Ruppert