I am making a multiplayer game in c# windows form application with web service which is requires us to put a timer on the gameform, so that when the countdown timer becomes 0, it would be the opponent's turn. Now, this is my timer code.
private void StartTimer()
{
timeLeft = 11;
while (TimerRunning)
{
if (timeLeft > 0)
{
if (this.InvokeRequired)
lb_Timer.Invoke((MethodInvoker)delegate ()
{
timeLeft = timeLeft - 1;
if (timeLeft < 10)
lb_Timer.Text = "0: 0" + timeLeft;
else
lb_Timer.Text = "0: " + timeLeft;
});
else
{
timeLeft = timeLeft - 1;
if (timeLeft < 10)
lb_Timer.Text = "0: 0" + timeLeft;
else
lb_Timer.Text = "0: " + timeLeft;
}
}
else
{
if (this.InvokeRequired)
lb_Timer.Invoke((MethodInvoker)delegate ()
{
TimerRunning = false;
lb_Timer.Text = "0:00";
});
else
{
TimerRunning = false;
lb_Timer.Text = "0:00";
}
break;
}
Thread.Sleep(2200);
}
}
Notes:
- the countdown timer span is 10 seconds, I gave the timeleft value 11 so that when the timer starts, it would start at exactly 10s.
- The thread.sleep becomes the interval for my timer, because 1000 or 1s is too fast, that's why I decided to make it to 2.2s.
- can you give me an advice on how to make the thread stop, when the user attacks, so that the timer would reset?
- can you give me any idea or tips on how should I implement my timer using the webservice? thank you!