views:

934

answers:

3

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?

A: 

You would have to use javascript/jquery to poll the server for changes. This is one of the more unfortunate side-effects of all this fancy-schmancy jquery/ajax stuff: people forget that the browser must poll the web server - it's a one way connection only, even if it does sometimes feel like a client winforms app. Ultimately, the browser must make a http post/get request of its own accord. Yes, you can emit client javascript ahead of time to tell it to do so, but this requires that you know when exactly to call back. It sounds like you have some arbitrary code that will be done when it's done, so in this case you must continually poll.

-Oisin

x0n
+1  A: 

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.

Chad Ruppert
+1  A: 

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.

Jason