Reputation: 36656
I want the server to desplay some text on a webpage.
I defined
<asp:Label id="label1" runat="server" />
and set
protected void Button1_Click(object sender, EventArgs e)
{
label1.Text = "bla";
timer = new System.Threading.Timer(new TimerCallback(DoSomething), null, 0, 10000);
}
private void DoSomething(object obj)
{
label1.Text = "bla 1";
}
bla is presented, but not bla1. When I debug I see the "bla 1" line is executed. Where do I do wrong?
Upvotes: 0
Views: 215
Reputation: 1
The reason is when you click the button the request/response process occurs. Your thread is not refreshing the page or its fragment in any way.
Possibly you can achieve required result with websockets or ajax long pooling - with comet.
Upvotes: 0
Reputation: 16018
ASP.Net runs the code on the server and spits the result back to the browser, once this is completed nothing that happens on the server will have any affect on the html in the browser.
Upvotes: 0
Reputation: 21881
You can't asynchronously change a label in another thread like that, once the response is sent back to the browser then nothing you do on the server will make any difference. You will need to do client side ujpdates using javascript.
Upvotes: 0
Reputation: 459
I would think that the new timer doesn't complete before the page response is sent. The thread is probably throwing an error and just shutting down.
Upvotes: 0
Reputation: 40149
By the time DoSomething() gets executed, the response has already been sent to the browser, and your code does nothing. Actually, I'm surprised you don't crash the app domain with it.
You should not attempt to use threading primitives like this in an asp.net application.
If you want to update the value sometime "later" than the initial page displaying, you'll need to look at Ajax.
Upvotes: 3