开发者

System.Threading.Timer example to run and display seconds until you click a button

I am having some issues creating an asp.net page using C# When you first click a button it starts the display of seconds via a label control. When you click the button again the seconds stop.

Currently开发者_开发问答 my code does just prints 0 and stops:

System.Threading.Timer Timer;
bool endProcess = false;
int i = 0;

protected void Page_Load(object sender, EventArgs e)
{

  Timer = new System.Threading.Timer(TimerCallback, null, 10, 10);
  Label1.Text = i.ToString();
  i++;
}

private void TimerCallback(object state)
{

  if (endProcess == true)
  {
    Timer.Dispose();
    return;
  }
}

public void Button1_Click(object sender, System.EventArgs e)
{
  endProcess = true;
}


You must set the label.text=i.toString(); in timecallback function not in page_load


For this to work in ASP.NET, you should not use System.Threading.Timer, because this runs on the server side and you need to have the client side updated periodically. You have afew options for a WEB based application.

Keep in mind that you do not push UI updates to a web browser, the web browser needs to pull or request the update. So, a naive solution would be to have the browser periodically do a postback to the web server to get the updated text for the label. Not a good solution, but I share this as the basic premise of the concept.

I think the best option would be to this entirely on the client side using a javascript timer and updating the DOM element with the new value. Take a look at the second and third example on this page http://www.w3schools.com/js/js_timing.asp

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜