Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
933 views
in Technique[技术] by (71.8m points)

multithreading - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...