Reputation: 51
I've read much on TcpClient and multithreading at stackoverflow but think I didn't find a clear answer to this.
I have an application with 3 identical threads. (calling the same method on each thread object)
Every thread creates his own (local) TcpClient instance and opens a tcp connection to his server (different IP addresses).
The threads are supposed to do the same things only on a different server. The 3 server machines are running identical server software.
Now the 3 threads start a server request 'at the same time'.
Are the TcpClient objects totally isolated on each thread ? Or may it be that the underlying streams are unwillingly shared ?
I got the feeling that sometimes a thread gets data that's not from 'his' server. For examlpe all threads are polling for a 'ready' flag. Only Server 1 is ready and sets the flag, but thread 1 AND thread 2 see the flag set.
There's a good chance that I'm doing things wrong. But it would help to surely know that communication on the TcpClient objects in this way is safe.
Thanks a lot for any suggestions, Ralf
PS: And yes, I am currently reading books and documentation on multithreading in C# 8-))
Upvotes: 0
Views: 210
Reputation: 26
Could be a problem with the port to which a server send the response back. Afaik the source port is determinatet automaticily depending on the programm which sends a request to a server. Perhaps the port determination does not differ between each threat, so the three simultaneous running threats recive an answer on the same port... but thats only my guess I am not very into TCP-stuff
Upvotes: 0
Reputation: 1063864
If the TcpClient
instances are separate, then they won't be sharing any state - you can use as many TcpClient
instances as you need. If data is leeching between threads, I can only assume that it is in your own code. A common cause of confusion here is captured variables (anything from a lambda / anon-method), which prior to C# 5 can be shared in ways that the casual reviewer might not anticipate. Without more info we can't say more, but no: they should not interfere with each-other.
Upvotes: 1