I’m making a server for a game and I need to save everyone’s second so I made :-
private static void SubmitChanges() {
while(true) {
try {
using(GameDBDataContext db = new GameDBDataContext()){
foreach(IHero hero in world.Entities.BattleEntities.OnlineHeros.Values) {
hero.Update(db);
}
}
} catch(Exception ex) {
Console.WriteLine(ex.ToString());
}
Thread.Sleep(1000);
}
}
Is that fine? and would it be fine if I have like 500 online heroes?
EDIT: Checking how long it takes :-
private void UpdateDatabase() {
try {
using(GameDBDataContext db = new GameDBDataContext()) {
foreach(IHero hero in world.Entities.BattleEntities.OnlineHeros.Values) {
DateTime now = DateTime.Now;
hero.Update(db);
DateTime after = DateTime.Now;
Console.WriteLine((now - after).Milliseconds);
}
}
} catch(Exception ex) {
Console.WriteLine(ex.ToString());
}
}
result :-
-13
-10
-13
-26
-19
-24
-25
-19
-27
-22
-19
-26
-25
-21
-24
-22
You can update this all in one sql request. Linq-to-sql has method SubmitChanges, that commit all changes in context. So you can accumulate changes on hero in loop and submit them after loop.
Where UpdateRecord is your Update method but exclude SubmitChanges.