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.
                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()))
                    int pos = result.IndexOf(RequestManager.responseDelimiter()) + RequestManager.responseDelimiter().Length;
                    result = result.Substring(0, pos);
                catch (Exception e)
                    ACGOutput.LogError("Notification Inner Error :: " + e.Message);
                result = "";

            return result;

Open in new window

Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

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

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?

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.

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today

From novice to tech pro — start learning today.