如何使用SignalR Hubs处理并发

时间:2015-08-18 16:11:12

标签: c# asp.net signalr

我有一个Game类,里面有一个玩家列表。

class Game {
  Player[] Players;
}

我有两种集线器方法:

OnDisconnected() {
  room.Players.Remove(3);
}

CalculateScore() {
  int score = room.Players[3].Score;
  // use score
}

OnDisconnected正在删除播放器,CalculateScore正在使用该播放器来计算分数。

当用户在CalculateScore正在运行时断开连接时会发生什么。

我该如何处理这种情况?

1 个答案:

答案 0 :(得分:0)

这与SignalR的实现没有多大关系,但更多的是针对您的用例的要求以及您对CalculateScore的结果所做的事情。

我会以下列方式处理这种情况:

    CalculateScore()
        {
           if(room.Players[3] == null)
              {
                //get the latest information on this user based on his Id from the
               //database and calculate his score based on that.
              }

             //if the user is still connected, calculate the score using
             // room.Players[3].Score
        }

这样,如果用户已经连接,你可以在没有数据库访问的情况下计算他的分数,因为你从模型中得到他的分数,如果他断开连接,你仍然可以计算他的分数(但是操作会慢一点,因为数据库访问)。

希望这会有所帮助。祝你好运!

相关问题