I am trying to build an interface for a game. The game runs for 1 minute. The GetStop method stops after 60 sec game. The play method starts the game and the quit method quit the game. Now ideally what I want is when I quit the game after 30 seconds, the timer should get reset and on click of the Play button, the timer should again run for 1 minute. So that the next game gets to run for 1 minute. If I press Quit button then again, the timer should be reset for the next game.
However, there seems to be a certain issue in my code. Whenever I execute quit method the timer seems to be saved at that state. So, If I quit a race in 30 seconds then the next race will last for only 30 seconds. If I quit a race in 50 seconds, the next race will last only 10 seconds. Ideally, the timer should get reset but it is not getting reset.
I am out of ideas here. Can anyone please provide some suggestions??
private async Task GetStop(CancellationToken token)
{
await Task.Run(async () =>
{
token.ThrowIfCancellationRequested();
await Task.Delay(TimeSpan.FromSeconds(60), token);
token.ThrowIfCancellationRequested();
if (!token.IsCancellationRequested)
{
sendMessage((byte)ACMessage.AC_ESCAPE);
}
}, token);
}
public async void Play()
{
sendMessage((byte)ACMessage.AC_START_RACE);
_cts.Cancel();
if (_cts != null)
{
_cts.Dispose();
_cts = null;
}
_cts = new CancellationTokenSource();
await GetStop(_cts.Token);
}
public void Quit()
{
_cts.Cancel();
if (_cts != null)
{
_cts.Dispose();
_cts = null;
}
//
}