Reputation:
I don't know much about threads, but I have a function in the main class of my console application called SendProcessCmd(string cmd). In my main() I create a process, and store the StreamWriter as a class member var, and my SendProcessCmd() issues the .WriteLine() commands to it.
I have another thread with a TCP server that listens for connections, then allows these to send commands to the process using Program.SendProcessCmd(). Is it safe to do this?
The safest method I can think of would be to find the running process in my server's thread, create a new StreamWriter, then issue the commands. However, this seems like a rather long way around to do the same thing.
Upvotes: 1
Views: 4807
Reputation: 53709
If I have understood you correctly, it sounds like both threads will be using the same StreamWriter. If that is correct, then you will need to at the very least synchronise the writes to the StreamWriter using a Monitor.
If each thread is using multiple calls to the Write method to build up a complete message you need to block other threads from writting for the entire duration that it takes to complete the component parts of the message otherwise your message components will become mixed-up, it is like having two people trying to write on the same piece of paper at the same time in the same location, each writting a different story.
Upvotes: 2
Reputation: 14605
The whole purpose of threads is that you can always call any function and access any data structure from any thread. There are gotcha's, though:
Upvotes: 3
Reputation: 984
Executing any code and accessing memory is all perfectly fine for any number of threads to do simultaneously. The thing you have to watch out for is two threads trying to write to the same area of memory
Upvotes: 1