Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Update panel from a server side thread

I am trying to develop a chat using aspx. I already got it working with asmx + winform but now I have problems with asmx + aspx.

Basically what I want to do is call the WebMethod CheckForMessages every two seconds and, if there are messages, add them to a list box inside an update panel and do UpdatePanel1.Update();.

The problem is that apparently I can' t do this using a thread like I do in my winform.

void check() {
  while (true) {
    Thread.Sleep(2000);
    string message = CheckForMessages();
    if (message != "") {
      ListBox1.Items.Add(message);
      UpdatePanel1.Update();
    }
  }
}

I start the thread like this:

protected void Page_Load(object sender, EventArgs e) {
  timer = new Thread(new ThreadStart(check));
  timer.Start();
}

It doesn't throw an exception or anything, the program runs as intended. The web service is called, a string is returned if there is a message, the thread adds the message to the list and calls UpdatePanel1.Update();. Yet the panel is not updated.

What could the problem be ?

like image 539
user1909612 Avatar asked Mar 09 '26 15:03

user1909612


1 Answers

In ASP.Net you can use timer control along with updatepanel.

<asp:UpdatePanel runat="server" ID="uxUpdatePanel" UpdateMode="Conditional" EnableViewState="true">
        <ContentTemplate>
            <div>
                <asp:Label ID="Label1" runat="server" style="display:none;"><%=GetMessageLog()%></asp:Label> 
                <asp:ListBox runat="server" ID="ListBox1" EnableViewState="true">

                </asp:ListBox>
            </div>           
        </ContentTemplate>
        <Triggers>
            <asp:AsyncPostBackTrigger ControlID="uxTimer" EventName="Tick" />
        </Triggers>
    </asp:UpdatePanel>
    <asp:Timer runat="server" ID="uxTimer" Interval="2000">
    </asp:Timer>

And in Code-behind you to code like:

public string GetMessageLog()
{
    string message = CheckForMessages();
    if (message != "") {
      ListBox1.Items.Add(message);      
    return DateTime.Now.ToLongTimeString();
}

This should work for you. But I will recommend you to use Javascript and JQuery to call Web-Service asynchronously with setTimeout function.

like image 88
Vishal Vaishya Avatar answered Mar 11 '26 04:03

Vishal Vaishya



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!