我正在制作游戏服务器,我需要保存每个人,所以我做了: -
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);
}
}
这样好吗?如果我有500名在线英雄会好吗?
编辑:检查需要多长时间: -
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());
}
}
结果: -
-13
-10
-13
-26
-19
-24
-25
-19
-27
-22
-19
-26
-25
-21
-24
-22
答案 0 :(得分:0)
您可以在一个sql请求中更新此全部内容。 Linq-to-sql有方法SubmitChanges,它提交上下文中的所有更改。所以你可以在循环中积累英雄的变化并在循环后提交它们。
private static void SubmitChanges()
{
while(true) {
try {
using(GameDBDataContext db = new GameDBDataContext()){
foreach(IHero hero in world.Entities.BattleEntities.OnlineHeros.Values) {
hero.UpdateRecord(db);
}
db.SubmitChanges();
}
} catch(Exception ex) {
Console.WriteLine(ex.ToString());
}
Thread.Sleep(1000);
}
}
UpdateRecord是您的Update方法,但不包括SubmitChanges。