简体   繁体   中英

Use static dictionary in asp.net web application

I use SignalR in my asp.net web application. Session state doesn't exist in SignalR hub, so I decided to save username <-> connectionId pair in static dictionary.

public static class UsernameConnectionsMaps
{
    private static Dictionary<string, string> data = new Dictionary<string, string>();

    public static void Add(string username, string connectionId)
    {
       data[username] = connectionId;
    } 

    public static string Get(string username)
    {
       return data[username];
    }

    public static void Remove(string username)
    {
       return data.Remove(username);
    }  
}

On a particular controller request, I want to send data to the client with signalR. Knowing the username of current user, I can easily get connectionId for the client and send data.

I use Get method in my controller. I use Add and Remove methods in hub's OnConnected() and OnDisconnected() methods respectively.

I am interested in, if this solution will have any problem regarding thread safety (or other) in my web application? What will be better approach?

If you use a static dictionary you will lose the ability to scale out your API. Each instance will keep a different static Dictionary, so notifications will not always reach their destination, consider azure signalr or some kind of persistent storage like redis.

The best you can do and it is what is said in the Microsoft documentation, map users to groups, even if it will produce groups with single users or a groups with many users that are actually the same user. Even if you will use Redis backplane or Azure SignalR , you will have the groups in all context and can communicate with them, add, remove and etc...

A single user can have multiple connections to a SignalR app. For example, a user could be connected on their desktop as well as their phone. Each device has a separate SignalR connection, but they're all associated with the same user. If a message is sent to the user, all of the connections associated with that user receive the message.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM