OnDisconnect方法是否应该在被触发之前等待默认的30秒?对我来说,它会在页面刷新时立即触发(F5)。
我有一个User对象,用于跟踪哈希集中的用户连接。
在我的中心,我有一本字典来跟踪已连接的用户。
OnConnected:我将该用户添加到字典中,如果用户已经存在,我只需将另一个connectionid添加到用户hashset。
OnDisconnected:我从调用用户hashset中删除了connectionId,如果他没有任何连接,我从字典中删除用户对象。
我需要跟踪用户对象,并且在每次刷新页面时都会丢失它(F5)因为OnDisconnected会立即被触发并删除仅用户连接和对象。当页面再次加载时,会创建一个新的用户对象,导致旧的用户对象被立即删除。
我的实现看起来像这样
private static readonly ConcurrentDictionary<string, User> Users
= new ConcurrentDictionary<string, User>();
public override Task OnConnected() {
string userName = Context.User.Identity.Name;
string connectionId = Context.ConnectionId;
var user = Users.GetOrAdd(userName, _ => new User {
Name = userName,
ConnectionIds = new HashSet<string>()
});
lock (user.ConnectionIds) {
user.ConnectionIds.Add(connectionId);
// TODO: Broadcast the connected user
}
return base.OnConnected();
}
public override Task OnDisconnected() {
string userName = Context.User.Identity.Name;
string connectionId = Context.ConnectionId;
User user;
Users.TryGetValue(userName, out user);
if (user != null) {
lock (user.ConnectionIds) {
user.ConnectionIds.RemoveWhere(cid => cid.Equals(connectionId));
if (!user.ConnectionIds.Any()) {
User removedUser;
Users.TryRemove(userName, out removedUser);
// You might want to only broadcast this info if this
// is the last connection of the user and the user actual is
// now disconnected from all connections.
Clients.Others.userDisconnected(userName);
}
}
}
return base.OnDisconnected();
}
答案 0 :(得分:0)
所以我通过在OnDisconnected方法中运行一个任务并将方法延迟x秒来解决这个问题,然后检查用户是否已经重新连接,如果他没有将他从列表中删除。
public override Task OnDisconnected(bool stopCalled)
{
Task mytask = Task.Run(() =>
{
UserDisconnected(Context.User.Identity.Name, Context.ConnectionId);
});
return base.OnDisconnected(stopCalled);
}
private async void UserDisconnected(string un, string cId)
{
await Task.Delay(10000);
string userName = un;
string connectionId = cId;
User user;
enqueuedDictionary.TryGetValue(userName, out user);
if (user != null)
{
lock (user.ConnectionIds)
{
user.ConnectionIds.RemoveWhere(cid => cid.Equals(connectionId));
if (!user.ConnectionIds.Any())
{
User removedUser;
enqueuedDictionary.TryRemove(userName, out removedUser);
ChatSession removedChatSession;
groupChatSessions.TryRemove(userName, out removedChatSession);
UpdateQ(removedUser.QPos);
}
}
}
}