我正在研究 ASP.net Web Api、SignalR,希望将消息发送给所有用户,在更新实体时锁定其他用户,但希望避免在 HUB 和 Web API 控制器中重复代码。
我希望通用代码代表所有实体的以下行为,而不是每个实体 1 个。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Microsoft.AspNet.SignalR;
using Microsoft.AspNet.SignalR.Hubs;
using SignalRGridDemo.Models;
using System.Data;
using System.Collections.Concurrent;
using System.Threading.Tasks;
namespace SignalRGridDemo.Hubs {
[HubName("employee")]
public class EmployeeHub : Hub {
private static ConcurrentDictionary<string, List<int>> _mapping = new ConcurrentDictionary<string, List<int>>();
private SignalRGridDemoContext db = new SignalRGridDemoContext();
public override Task OnConnected() {
_mapping.TryAdd(Context.ConnectionId, new List<int>());
Clients.All.newConnection(Context.ConnectionId);
return base.OnConnected();
}
public void Lock(int id) {
var employeeToPatch = db.Employees.Find(id);
employeeToPatch.Locked = true;
db.Entry(employeeToPatch).State = EntityState.Modified;
db.SaveChanges();
Clients.Others.lockEmployee(id);
_mapping[Context.ConnectionId].Add(id);
}
public void Unlock(int id) {
UnlockHelper(id);
_mapping[Context.ConnectionId].Remove(id);
}
private void UnlockHelper(int id) {
var employeeToPatch = db.Employees.Find(id);
employeeToPatch.Locked = false;
db.Entry(employeeToPatch).State = EntityState.Modified;
db.SaveChanges();
Clients.Others.unlockEmployee(id);
}
public override Task OnDisconnected() {
foreach (var id in _mapping[Context.ConnectionId]) {
UnlockHelper(id);
}
var list = new List<int>();
_mapping.TryRemove(Context.ConnectionId, out list);
return base.OnDisconnected();
}
}
}