c# incorrect port used on multithreaded application

I have a multitreaded application that has TCP connections on each thread.

The application has one main class which creates 3 classes that are used by their respective threads. Each has a procedure that its thread calls to do the work.

Each class also has its own TcpClient and NetworkStreams that connect to either 1 or 2 servers. The connections are keept open under normal circumstances and so the ports they use are consistant.

Occasionally I have been getting a situation where the port from 1 thread is used by another. Today for instance the incorrect port was used 4 times in a row and then everything stabalized again.

I have used the server logs (which contain all IP address/port information) for each request and response to find this behaviour.

The only thing that the connections have in common is a  utility class with a STATIC method that is used for the request/Response. This method takes a Networkstream object and String(request) as parameters.

Has anyone seen or heard of this sort of cross tread behaviour before?
public static String DoRequestResponse(NetworkStream stream, String Request)
        {
            SendRequest(stream, Request);

            String result = "";
            byte[] myReadBuffer = new byte[100000];
            StringBuilder myCompleteMessage = new StringBuilder();
            int numberOfBytesRead = 0;
            // Incoming message may be larger than the buffer size.
            do
            {
                numberOfBytesRead = stream.Read(myReadBuffer, 0, myReadBuffer.Length);
                myCompleteMessage.AppendFormat("{0}", Encoding.ASCII.GetString(myReadBuffer, 0, numberOfBytesRead));
            }
            while (stream.DataAvailable);

            result = myCompleteMessage.ToString();

            if (result.Contains(RequestManager.responseDelimiter()))
            {
                try
                {
                    int pos = result.IndexOf(RequestManager.responseDelimiter()) + RequestManager.responseDelimiter().Length;
                    result = result.Substring(0, pos);
                }
                catch (Exception e)
                {
                    ACGOutput.LogError("Notification Inner Error :: " + e.Message);
                }
            }
            else
            {
                result = "";
            }

            return result;
        }

Open in new window

LVL 1
jetbetAsked:
Who is Participating?
 
jetbetAuthor Commented:
I have tracked down the issue and it is not the cross tread contamination that I suspected.

Thanks for the help and sorry for any time wastage I have caused.
0
 
Mahmoud_Al_HattabCommented:
Dear jetbet,
 If I got you properly, you want for each tcpclient to have its own port so same port is not conflecting with other connections. OK, when you create the TcpClient assigna port. make the port be assigned by a public static variable that gets incremented every time it is used. Volatile for integers is atomic and can not two threads share the same value for it.

For a more complicated solution, use lock, or any other synchronization method between threads not to share the same port.
volatile public static int port = 1000;
TcpClient tcp = new TcpClient("hostname", port++);

Open in new window

0
 
jetbetAuthor Commented:
At the moment when each Thread worker class is created and the connection set up, the system assigns an unused port number.

We may then have 20,000 or so request response pairs where the correct port is used by each thread.(this number is not set and could be anything)

What then seems to happen is that one class will use the port number from another thread for say 3 or 4 sends and then revert back to the port number it is supposed to use and do many more request/responses before this happens again.

Yesterday I had the system running for 16 hours and had 12 instances, out of well over 100,000, of this happening.

As the system allocation of the port numbers seems to work fine, I would prefer not to hard code port ranges into it unless I am sure that this is the issue.

I was wondering if there was some sort of known issue around this sort of behaviour or if in fact I should create instances of my request utility class for each thread rather than relying on the fact that this utility class and functions are static.

Does anyone know of ant cross thread contamination when using Static utility functions in this way?

0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.