1

Each time a client connects to my server, I create a new instance of the class ClientObject. That new instance will start with the constructor:

public ClientObject(TcpClient _Socket, int _ConnectionID)
        {
            if (_Socket == null) return;

            Socket = _Socket;
            ConnectionID = _ConnectionID;

            Socket.NoDelay = true;

            Socket.ReceiveBufferSize = 4096;
            Socket.SendBufferSize = 4096;

            myStream = Socket.GetStream();

            ReceiveBuffer = new byte[4096];

            myStream.BeginRead(ReceiveBuffer, 0, Socket.ReceiveBufferSize, ReceiveCallback, null);
        }

After receiving some message from the corresponding client, the asynchronous callback method ReceiveCallback is called:

private void ReceiveCallback(IAsyncResult result)
        {
                int readBytes = myStream.EndRead(result);
                if (readBytes <= 0)
                {
                    CloseConnection();
                    return;
                }
                byte[] newBytes = new byte[readBytes];
                Buffer.BlockCopy(ReceiveBuffer, 0, newBytes, 0, readBytes);
                ServerHandleData.HandleData(ConnectionID, newBytes);
                myStream.BeginRead(ReceiveBuffer, 0, Socket.ReceiveBufferSize, ReceiveCallback, null);
        }

Now, the important part here is the ServerHandleData.HandleData(ConnectionID, newBytes); line (HandleData is a static method). Let's assume at least 2 clients sent messages. Then this static method will be called more than once. In that case, will we be running on multiple threads? Or will each call wait for the previous one to finish? In that case, would it be possible to create a more efficient model that deals with clients concurrently?

Thanks!

  • [It won't hurt](https://stackoverflow.com/questions/3037637/c-sharp-what-if-a-static-method-is-called-from-multiple-threads) (as long as `ServerHandleData.HandleData` is stateless). But why is `ServerHandleData.HandleData` static? Why not use an injected instance so it can be unit tested? – Andrew S Feb 09 '20 at 00:12
  • What I really want to know is whether ```ServerHandleData.HandleData``` is called from multiple threads or not. I actually want it to be called from multiple threads but I am not sure whether the asynchronous callback function does that. The function is indeed stateless. However, I am not familiar with injected instances. – randomDev111 Feb 09 '20 at 00:21
  • Yes, it can be called by multipl threads, so any shared data must be thread-safe. – Jeroen van Langen Feb 09 '20 at 00:22
  • 1
    A constructor should only setup the state of an object. Kicking off an IO operation should be done by a call to a separate method. Depending on how you use that instance you create, it might make more sense for that code to be in a static method to begin with. – juharr Feb 09 '20 at 01:53

0 Answers0