Auto-delete ended games after delay
Schedule game removal after a short delay when a game ends. Adds ScheduleGameDeletion which starts a background task, waits (5s), checks the repository for the game and its Ended state, destroys it, and notifies the hub with "GameDestroyed". Calls to ScheduleGameDeletion were added after Win, Draw, and PlayerDisconnected; PlayerDisconnected no longer returns the SendAsync task but returns a completed task after scheduling deletion.
This commit is contained in:
@@ -77,6 +77,8 @@ public class GameManager(IGameRepository gameRepository, IHubContext<GameHubSock
|
|||||||
Method = "Win",
|
Method = "Win",
|
||||||
Player = winPlayer
|
Player = winPlayer
|
||||||
});
|
});
|
||||||
|
|
||||||
|
ScheduleGameDeletion(game.Id, TimeSpan.FromSeconds(5));
|
||||||
}
|
}
|
||||||
|
|
||||||
if (game.Field.IsFull())
|
if (game.Field.IsFull())
|
||||||
@@ -87,6 +89,8 @@ public class GameManager(IGameRepository gameRepository, IHubContext<GameHubSock
|
|||||||
{
|
{
|
||||||
Method = "Draw"
|
Method = "Draw"
|
||||||
});
|
});
|
||||||
|
|
||||||
|
ScheduleGameDeletion(game.Id, TimeSpan.FromSeconds(5));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -102,10 +106,30 @@ public class GameManager(IGameRepository gameRepository, IHubContext<GameHubSock
|
|||||||
|
|
||||||
game.RemovePlayer(playerConnectionId);
|
game.RemovePlayer(playerConnectionId);
|
||||||
game.EndGame();
|
game.EndGame();
|
||||||
return hubContext.Clients.Group(game.Id).SendAsync("GameEnded", new
|
hubContext.Clients.Group(game.Id).SendAsync("GameEnded", new
|
||||||
{
|
{
|
||||||
Method = "PlayerDisconnected",
|
Method = "PlayerDisconnected",
|
||||||
Player = player
|
Player = player
|
||||||
});
|
});
|
||||||
|
|
||||||
|
ScheduleGameDeletion(game.Id, TimeSpan.FromSeconds(5));
|
||||||
|
|
||||||
|
return Task.CompletedTask;
|
||||||
|
}
|
||||||
|
|
||||||
|
private void ScheduleGameDeletion(string gameId, TimeSpan delay)
|
||||||
|
{
|
||||||
|
_ = Task.Run(async () =>
|
||||||
|
{
|
||||||
|
await Task.Delay(delay);
|
||||||
|
|
||||||
|
var g = gameRepository.GetOne(gameId);
|
||||||
|
if (g != null && g.State == GameState.Ended)
|
||||||
|
{
|
||||||
|
gameRepository.Destroy(gameId);
|
||||||
|
|
||||||
|
await hubContext.Clients.Group(gameId).SendAsync("GameDestroyed");
|
||||||
|
}
|
||||||
|
});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
Reference in New Issue
Block a user