这是我的中心:
[HubName("marketWatch")]
public class MarketWatchHub : Hub
{
public override Task OnConnected()
{
SocketCommunicator.Instance.UserConnected(Context.ConnectionId, Context.User.Identity.Name);
return base.OnConnected();
}
public override Task OnDisconnected()
{
SocketCommunicator.Instance.UserDisconnected(Context.ConnectionId);
return base.OnDisconnected();
}
public override Task OnReconnected()
{
// TODO: implement...
return base.OnReconnected();
}
public List<MarketDataResponse> GetAllMarketWatchData()
{
return SocketCommunicator.Instance.MarketDataList;
}
}
这是 SocketCommunicator 类的简化版本:
public class SocketCommunicator
{
private static SocketCommunicator _Instance = new SocketCommunicator();
public static SocketCommunicator Instance
{
get { return SocketCommunicator._Instance; }
}
private Socket socket { get; set; }
private readonly object lockObj = new object();
private IHubContext hubContext;
private List<UserDetail> connectedUsers;
public List<MarketDataResponse> MarketDataList;
private SocketCommunicator() { }
public void UserConnected(string connectionId, string username)
{
lock (lockObj)
{
connectedUsers.Add(new UserDetail() { ConnectionId = connectionId, UserName = username });
}
}
public void UserDisconnected(string connectionId)
{
lock (lockObj)
{
connectedUsers.RemoveAll(ud => ud.ConnectionId == connectionId);
}
}
public void GetMarketData()
{
// Do something and set this.MarketDataList
}
}
当我按 F5 并调试我的应用程序时,它就像一个魅力。当用户登录时,我的集线器中的 OnConnected 方法被调用,当用户注销时,OnDisconnected 方法被调用。但是,如果用户登录并关闭他/她的浏览器,则不会调用 OnDisconnected 方法。这意味着及时,我的 connectedUsers 列表将包含大量未真正连接的 UserDetail 对象。我怎样才能避免这种情况?有没有更好的方法来存储用户 - 连接 ID 关联?
提前致谢,