public partial class _Default : System.Web.UI.Page
{
private static Stopwatch timer = new Stopwatch();
Thread timeThread = new Thread(timeKeeper);
private static int min = 0, sec = 0;
protected void Page_Load(object sender, EventArgs e)
{
}
protected void startstop_Click(object sender, EventArgs e)
{
timeThread.Start();
if(timer.IsRunning()) {timer.Stop}
else timer.Start();
}
private static void timeKeeper()
{
while (timer.IsRunning)
{
mydelegate();
}
}
private static void mydelegate()
{
_Default temp = new _Default();
temp.Update();
}
private void Update()
{
min = timer.Elapsed.Minutes;
sec = timer.Elapsed.Seconds;
time.Text = min + ":" + sec;
}
}
what i want to do is have a button that controls the a stopwatch, when you click it it starts, click it again it stops. I figured the best way to do it is with a thread if i want the time.text display to continue update and to be able to click the button still. when i run the above program it gets to time.text = min + “:” + sec; and throws a nullreferenceexception. Any help on how to fix this would be greatly appreciated. I am semi new to programming in C#/asp.net.
Is there a better way of working with delegates then this. I have spent hours looking up how to use them with not many usual/easy to understand tutorials or blogs
I’m not sure where to begin.
Remember you are programming a webpage, and every call to a server result in a new webpage life cycle on the server. So using threads in a webpage will not result in the correct behaviour.
To get the kind of behaviour you want, you’ll have to do the timer and click handling on the client instead of the server. You can use jQuery to facilitate in this. One other option is to use ajax if you have to keep the server up-to-date.