c# - 如何使用 SignalR Hubs 处理并发

标签 c# asp.net signalr

我有一个包含玩家列表的游戏类。

class Game {
  Player[] Players;
}

我有两种集线器方法:

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

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

OnDisconnected 正在删除一个玩家,CalculateScore 正在使用该玩家计算分数。

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

我该如何处理这种情况?

最佳答案

这与 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
        }

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

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

关于c# - 如何使用 SignalR Hubs 处理并发,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32077496/

相关文章:

azure - 使用 Azure SignalR 服务连接到 SignalR Hub

javascript - 通过 Ajax 将对象数组 (Javascript) 转换为 C#

c# - 如何对先前的 InvokeMember 结果调用 InvokeMember?

c# - Head First C# Lab1 A Day at the Races 调用的方法未执行

c# - 为什么要升级到 c# 4.0?

c# - 我可以在某些情况下关闭模拟吗

swift - 使用 Swift 3.0 的 SignalR 实现

asp.net - 问题设置订阅查询通知

c# - 如何将数组作为参数发送到 C# 中的 quartz 计划作业?

javascript - SignalR 2.2 客户端未收到任何消息