Socket Server, locking and slowdowns

ertaboy356b

Old School Gamer
Reaction score
86
So creating this monitoring application is a really big challenge for me. Not only that it requires a large amount of database interaction, but it also needs to be realtime. The establishment I'm working on should have at least 500 active employees using the program at the same time which means a lot of stress to the suppose socket server I'm working.

The challenge is how to make the socket server thread-safe and at the same time fast. The socket sending issue has been resolve and I am now facing some "collections changed" problems due to multi-threading. I've implemented locking but that makes the program slow since it has to wait for certain threads to stop using the collections.

So if I create a new instance of the object like for example:
Code:
List<UserData> exclusiveUserDataList;
lock (UserDataList) {
  exclusiveUserDataList = UserDataList.ToList();
}
foreach (var userData in exclusiveUserDataList) {
  // Do Something
  lock(UserDataList) UserDataList.Remove(userData);
}
will it be better than doing this? :
Code:
lock (UserDataList) {
foreach (var userData in UserDataList) {
  // Do Something
   UserDataList.Remove(userData);
}
}

I feel like I should really change how the code works or else I'll be dead -_-

Might be important info: the program has at least 50 packet handlers (which runs functions depending on the packetType received asynchronously).
 

Monovertex

Formerly Smith_S9
Reaction score
1,461
So what happens if some other thread / process / whatever you have changes the UserDataList? For example:

Code:
List<UserData> exclusiveUserDataList;
lock (UserDataList) {
  exclusiveUserDataList = UserDataList.ToList();
}
 
// Something occurs here: for example the UserDataList is emptied, or even worse, deleted.
// You'll get an exception or some unforeseen consequences in the for.
 
foreach (var userData in exclusiveUserDataList) {
  // Do Something
  lock(UserDataList) UserDataList.Remove(userData);
}

However, I need more information. It really depends in what does Do Something mean. I mean, when you copy the list, if there's Object in there, as far as I know the copying is shallow, so it won't copy the Objects as well, it'll only copy the references. If someone deletes the object inside, you'll no longer have that.

Provide more context and I'll be able to help you more.

Also, what exactly is UserDataList? Is it a class or a variable? If it's a variable why does it starts with capital U?...

EDIT: If you can provide the larger picture, as what exactly is done with the list in the other processes, we might be able to find another planning for your activities with the list, maybe make it faster. When using locks on a variable modified by a lot of processes and those modifications are the entire purpose of the module, then you're basically serializing all the stuff and you could just as well use a single process, you didn't gain anything. Some things can't be parallel, there's that too :p.
 

ertaboy356b

Old School Gamer
Reaction score
86
UserDataList is an ObservableCollection. It's actually a class-wide variable.
ObservableCollection<UserData> UserDataList;

UserData is this:
Code:
    public class UserData : PropertyChangedBase
    {
        private int _userId;
        public int UserId
        {
            get { return _userId; }
            set
            {
                _userId = value;
                NotifyOfPropertyChange(() => UserId);
            }
        }
 
        private string _userCode;
        public string UserCode
        {
            get { return _userCode; }
            set
            {
                _userCode = value;
                NotifyOfPropertyChange(() => UserCode);
            }
        }
 
        private int _projectId;
        public int ProjectId
        {
            get { return _projectId; }
            set
            {
                _projectId = value;
                NotifyOfPropertyChange(() => ProjectId);
            }
        }
 
        private string _projectName;
        public string ProjectName
        {
            get { return _projectName; }
            set
            {
                _projectName = value;
                NotifyOfPropertyChange(() => ProjectName);
            }
        }
 
        private string _position;
        public string Position
        {
            get { return _position; }
            set
            {
                _position = value;
                NotifyOfPropertyChange(() => Position);
            }
        }
 
        private bool _isNightShift;
        public bool IsNightShift
        {
            get { return _isNightShift; }
            set
            {
                _isNightShift = value;
                NotifyOfPropertyChange(() => IsNightShift);
            }
        }
 
        private int _rights;
        public int Rights
        {
            get { return _rights; }
            set
            {
                _rights = value;
                NotifyOfPropertyChange(() => Rights);
            }
        }
 
        private Connection _connection;
        public Connection Connection
        {
            get { return _connection; }
            set
            {
                _connection = value;
                NotifyOfPropertyChange(() => Connection);
            }
        }
 
        private string _ipAddress;
        public string IPAddress
        {
            get { return _ipAddress; }
            set
            {
                _ipAddress = value;
                NotifyOfPropertyChange(() => IPAddress);
            }
        }
 
        private int _port;
        public int Port
        {
            get { return _port; }
            set
            {
                _port = value;
                NotifyOfPropertyChange(() => Port);
            }
        }
 
        private bool _onQuery;
        public bool OnQuery
        {
            get { return _onQuery; }
            set
            {
                _onQuery = value;
                NotifyOfPropertyChange(() => OnQuery);
            }
        }
 
        private int _loginId;
        public int LoginId
        {
            get { return _loginId; }
            set
            {
                _loginId = value;
                NotifyOfPropertyChange(() => LoginId);
            }
        }
 
        private int _dropCount;
        public int DropCount
        {
            get { return _dropCount; }
            set
            {
                _dropCount = value;
                NotifyOfPropertyChange(() => DropCount);
            }
        }
    }

'Connection' is an object with socket features like for example SendObject().

I'll give a sample code:

Code:
private void Login(Connection connection, UserLoginData message) {
    var userIp = connection.IPAddress;
    var userPort = connection.Port;
    var data = new UserData()
    {
        UserCode = message.UserCode,
        UserId = message.UserId,
        ProjectId = message.ProjectId,
        ProjectName = message.ProjectName,
        // more variables
    };
    lock (UserDataList) UserDataList.Add(data);
    Console.WriteLine(data.UserCode + " has Logged in!");
   
    // Notify Staff
    List<UserData> dataList;
    lock (UserDataList) dataList = UserDataList.Where(p => p.rights > 0).ToList();
    // Send Message to Staffs
    for (var i = 0; i < dataList.Count; i++) SendObject(dataList[i], "Login", message);
}
 
private void Logout(Connection connection, UserLogoutData message) {
    UserData remove;
    List<UserData> userDataList;
    lock(UserDataList) userDataList = UserDataList.Where(p => p.UserId == message.UserId).Where(p => p.Connection == connection).ToList();
    for (var i = 0; i < userDataList.Count; i++)
    {
        remove = userDataList[i];
        Console.WriteLine("{0} has Logged Out!", userDataList[i].UserCode);
    }
   
    // Remove User
    lock(UserDataList) UserDataList.Remove(remove);
   
    // Notify Staffs
    lock(UserDataList) userDataList = UserDataList.Where(p => p.Position.ToLower() == "staff").ToList();
    // Send Messages to staffs
    for(var i = 0; i < userDataList.Count; i++) SendObject(userDataList[i], "Logout", message);
}
 
 
// Here's the code that let's the staff sends a message to all projects
private void ProjectMessage(Connection connection, SendProjectMessageData message)
{
    List<UserData> userDataList;
    lock(UserDataList) userDataList = UserDataList.Where(p => (p.ProjectId == message.ToProjectId) || (message.ToProjectId == 0)).ToList();
    for (var i = 0; i < userDataList.Count; i++) SendObject(userDataList[i], "ProjectMessage", message);
}
 
 
// And some members I used in this example
private readonly int _maxSocketDropCount = 10;
 
private void SendObject(UserData u, string packetType, object message)
{
    Task.Factory.StartNew(() =>
    {
    for (var i = 0; i < _maxSocketDropCount; i++)
    {
        try
        {
        u.Connection.SendObject(packetType, message);
        return;
        //Console.WriteLine("{0} has been notified", u.UserCode);
        }
        catch (Exception ex)
        {
        Console.WriteLine(ex.Message + " Resending....");
        }
    }
    });
}

I think there's no problem with 'deleting objects' since objects are never deleted, just removed from the list.

Imagine people are logging in and logging out at the same time.
 
General chit-chat
Help Users
  • No one is chatting at the moment.
  • The Helper The Helper:
    If you are new to the site please check out the Recipe and Food Forum https://www.thehelper.net/forums/recipes-and-food.220/
  • Monovertex Monovertex:
    How come you're so into recipes lately? Never saw this much interest in this topic in the old days of TH.net
  • Monovertex Monovertex:
    Hmm, how do I change my signature?
  • tom_mai78101 tom_mai78101:
    Signatures can be edit in your account profile. As for the old stuffs, I'm thinking it's because Blizzard is now under Microsoft, and because of Microsoft Xbox going the way it is, it's dreadful.
  • The Helper The Helper:
    I am not big on the recipes I am just promoting them - I use the site as a practice place promoting stuff
    +2
  • Monovertex Monovertex:
    @tom_mai78101 I must be blind. If I go on my profile I don't see any area to edit the signature; If I go to account details (settings) I don't see any signature area either.
  • The Helper The Helper:
    You can get there if you click the bell icon (alerts) and choose preferences from the bottom, signature will be in the menu on the left there https://www.thehelper.net/account/preferences
  • The Helper The Helper:
    I think I need to split the Sci/Tech news forum into 2 one for Science and one for Tech but I am hating all the moving of posts I would have to do
  • The Helper The Helper:
    What is up Old Mountain Shadow?
  • The Helper The Helper:
    Happy Thursday!
    +1
  • Varine Varine:
    Crazy how much 3d printing has come in the last few years. Sad that it's not as easily modifiable though
  • Varine Varine:
    I bought an Ender 3 during the pandemic and tinkered with it all the time. Just bought a Sovol, not as easy. I'm trying to make it use a different nozzle because I have a fuck ton of Volcanos, and they use what is basically a modified volcano that is just a smidge longer, and almost every part on this thing needs to be redone to make it work
  • Varine Varine:
    Luckily I have a 3d printer for that, I guess. But it's ridiculous. The regular volcanos are 21mm, these Sovol versions are about 23.5mm
  • Varine Varine:
    So, 2.5mm longer. But the thing that measures the bed is about 1.5mm above the nozzle, so if I swap it with a volcano then I'm 1mm behind it. So cool, new bracket to swap that, but THEN the fan shroud to direct air at the part is ALSO going to be .5mm to low, and so I need to redo that, but by doing that it is a little bit off where it should be blowing and it's throwing it at the heating block instead of the part, and fuck man
  • Varine Varine:
    I didn't realize they designed this entire thing to NOT be modded. I would have just got a fucking Bambu if I knew that, the whole point was I could fuck with this. And no one else makes shit for Sovol so I have to go through them, and they have... interesting pricing models. So I have a new extruder altogether that I'm taking apart and going to just design a whole new one to use my nozzles. Dumb design.
  • Varine Varine:
    Can't just buy a new heatblock, you need to get a whole hotend - so block, heater cartridge, thermistor, heatbreak, and nozzle. And they put this fucking paste in there so I can't take the thermistor or cartridge out with any ease, that's 30 dollars. Or you can get the whole extrudor with the direct driver AND that heatblock for like 50, but you still can't get any of it to come apart
  • Varine Varine:
    Partsbuilt has individual parts I found but they're expensive. I think I can get bits swapped around and make this work with generic shit though
  • Ghan Ghan:
    Heard Houston got hit pretty bad by storms last night. Hope all is well with TH.
  • The Helper The Helper:
    Power back on finally - all is good here no damage
    +2
  • V-SNES V-SNES:
    Happy Friday!
    +1
  • The Helper The Helper:
    New recipe is another summer dessert Berry and Peach Cheesecake - https://www.thehelper.net/threads/recipe-berry-and-peach-cheesecake.194169/
  • The Helper The Helper:
    I think we need to add something to the bottom of the front page that shows the Headline News forum that has a link to go to the News Forum Index so people can see there is more news. Do you guys see what I am saying, lets say you read all the articles on the front page and you get to the end and it just ends, no kind of link for MOAR!

      The Helper Discord

      Staff online

      Members online

      Affiliates

      Hive Workshop NUON Dome World Editor Tutorials

      Network Sponsors

      Apex Steel Pipe - Buys and sells Steel Pipe.
      Top