简体   繁体   English

如何使用SignalR Hubs处理并发

[英]How to handle concurrency with SignalR Hubs

I have a Game class holding a list of players. 我有一个Game类,里面有一个玩家列表。

class Game {
  Player[] Players;
}

I have two hub methods: 我有两个集线器方法:

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

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

OnDisconnected is removing a player, CalculateScore is using that player to calculate score. OnDisconnected正在移除玩家, CalculateScore正在使用该玩家来计算得分。

What happens when user disconnects while CalculateScore is running. CalculateScore正在运行时,用户断开连接时会发生什么。

How do I handle this situation? 我该如何处理这种情况?

This doesn't have much to do with the implementation of SignalR, but more with what are the requirements for your use case and what you do with the result of CalculateScore . 这与SignalR的实现没有多大关系,但更多的是对您的用例有什么要求以及您对CalculateScore的结果做了什么。

I would handle this situation in the following manner: 我会用以下方式处理这种情况:

    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
        }

This way, if the user is connected you calculate his score without database access, because you get his score from the model, and if he disconnected, you still get to calculate his score (but the operation will be slower, because of the database access). 这样,如果用户已连接,则计算他的分数而无需数据库访问,因为您从模型中获得了分数,如果他断开连接,您仍然可以计算他的分数(但由于数据库访问,操作会更慢) )。

Hope this helps. 希望这可以帮助。 Best of luck! 祝你好运!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM