简体   繁体   中英

How to handle concurrency with SignalR Hubs

I have a Game class holding a list of players.

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.

What happens when user disconnects while CalculateScore is running.

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 .

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!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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