SignalR IHubContext和线程安全性

3
在下面的代码示例中,我实现了一个SignalR Hub,它应该实现以下功能:
  • 客户端可以通过调用Hub的Subscribe方法并提供一些id作为组名来监听Foo实例的更改。
  • 取消订阅类似于调用Unsubscribe方法。
  • Web应用程序的服务层可以通过调用OnFooChanged通知连接到适当id(组)的已订阅客户端发生了更改。
使用单例对于Hub上下文是安全的吗?还是我需要在OnFooChanged内每次获取它?欢迎就其他方法的实现提供反馈,毕竟我是新手SignalR。
[Export]
public class FooHub : Hub
{
  private static readonly Lazy<IHubContext> ctx = new Lazy<IHubContext>(
    () => GlobalHost.ConnectionManager.GetHubContext<FooHub>());

  #region Client Methods 

  public void Subscribe(int[] fooIds)
  {
    foreach(var fooId in fooIds)
      this.Groups.Add(this.Context.ConnectionId, fooId.ToString(CultureInfo.InvariantCulture));
  }

  public void Unsubscribe(int[] fooIds)
  {
    foreach (var fooId in fooIds)
      this.Groups.Remove(this.Context.ConnectionId, fooId.ToString(CultureInfo.InvariantCulture));
  }

  #endregion // Client Methods

  #region Server Methods

  /// <summary>
  /// Called from service layer when an instance of foo has changed
  /// </summary>
  public static void OnFooChanged(int id)
  {
    ctx.Value.Clients.Group(id.ToString(CultureInfo.InvariantCulture)).onFooChanged();
  }

  #endregion // Server Methods
}
1个回答

6
引用自服务器广播教程

你需要一次性获取上下文的两个原因: 获取上下文是一个昂贵的操作,只需获取一次即可确保客户端接收消息的顺序正确。

换句话说:使用懒惰单例是安全且推荐的方法。如果每次向客户端发送消息时都获取新的上下文,则可能导致消息按您预期的不同顺序发送。
我不知道您为什么经常需要获取新的上下文。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接