开发者

How can I synchronize access to a private static field of a class by its methods?

开发者 https://www.devze.com 2023-02-19 17:59 出处:网络
I am implementing COMET in my MVC web application by using the PokiIn library for pushing notifications to clients.

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.开发者_StackOverflow社区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.


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.


I think you should use lock(clientsList){} whenever you want to update your dictionary

0

精彩评论

暂无评论...
验证码 换一张
取 消