如何通过类的方法同步对类的私有静态字段的访问?
我正在我的 MVC Web 应用程序中实现 COMET,使用 PokiIn 库向客户端推送通知。
每当客户端连接时,ClientId 在 CometWorker 类的 OnClientConnected 事件中可用:
public static Dictionary<int, string> clientsList
= new Dictionary<int, string>();
public static string clientId = "";
static void OnClientConnected(string clientId,
ref Dictionary<string, object> list)
{
BaseController.clientId = clientId;
}
我将处理程序中收到的 clientId 分配给控制器的静态 ClientId。然后,当调用 Handler 操作时,我将此 ClientId 映射到登录用户的身份:-
public ActionResult Handler()
{
if (User.Identity.IsAuthenticated)
{
if (clientsList.Keys.Contains(currentUser.UserId))
clientsList[currentUser.UserId] = clientId;
else
clientsList.Add(currentUser.UserId, clientId);
}
return View();
}
因为多个请求将由服务器上的不同线程提供服务,所以每个请求都将在这两种方法中访问静态 ClientId。
如何同步其访问,以便在两个方法(OnClientConnected 和 Handler)中完成一个请求之前,另一个请求会等待它?
如果我的问题不清楚,请告诉我。我会努力进一步改进它。
I am implementing COMET in my MVC web application by using the PokiIn library for pushing notifications to clients.
Whenever a client connects, the ClientId is available in the OnClientConnected event of the CometWorker class:
public static Dictionary<int, string> clientsList
= new Dictionary<int, string>();
public static string clientId = "";
static void OnClientConnected(string clientId,
ref Dictionary<string, object> list)
{
BaseController.clientId = clientId;
}
I assign the the clientId received in the handler to the static ClientId of controller. And then when the Handler action is called, I map this ClientId to the Identity of the logged in user:-
public ActionResult Handler()
{
if (User.Identity.IsAuthenticated)
{
if (clientsList.Keys.Contains(currentUser.UserId))
clientsList[currentUser.UserId] = clientId;
else
clientsList.Add(currentUser.UserId, clientId);
}
return View();
}
Because multiple requests will be served by different threads on the server, each will access the static ClientId in both the methods.
How can I synchronize its access, so that untill one request is done with it in both the methods (OnClientConnected and Handler), the other request waits for it ?
Please tell me if my question is not clear. I will try to improve it further.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
将 clientid 存储在用户会话中,而不是存储在控制器上的静态变量中。它需要位于与用户相关的数据中,而不是整个应用程序中。或者更好的是,在客户端连接时解析名称/ID 查找。
Store the clientid in the user's session not in a static variable on the controller. It needs to be in data associated with the user not the entire application. Or better yet, resolve the name/id lookup when the client connects.
我认为每当您想要更新字典时都应该使用
lock(clientsList){}
I think you should use
lock(clientsList){}
whenever you want to update your dictionary