3

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?

eguneys
  • 6,028
  • 7
  • 31
  • 63
  • Read this post by one of the lead devs http://forums.asp.net/t/1876548.aspx?Concurrency+within+scaled+out+signalr concurrency is something you will need to handle in your app logic. – timothyclifford Aug 18 '15 at 16:18
  • Also this http://stackoverflow.com/questions/17070287/signalr-adding-removing-connections-from-a-dictionary-and-finding-group-values-f another one of the SignalR developers. Suggests using ConcurrentDictionary to manage player connctions. – timothyclifford Aug 18 '15 at 16:19
  • @timothyclifford, could you provide an answer to: a. is this a real concern? b. how should I structure my data to deal with this easier? c. what libraries can I leverage? – eguneys Aug 18 '15 at 16:20
  • The scenario you're talking about is a client disconnecting while you're calculating their score. It may be a concern but for this case I believe it is enough for you to simply check the player exists before calculating and returning the score. If the client has disconnected in the meantime, this will be handled by the framework. There's no point writing additional logic or using libraries unless your requirements warrant it. – timothyclifford Aug 18 '15 at 16:25

1 Answers1

0

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!

radu-matei
  • 3,469
  • 1
  • 29
  • 47