Is it safe to call a function in another thread?
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 St开发者_StackOverflow社区reamWriter 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.
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:
- You should always consider concurrency issues, locking and dead-lock avoiding etc.
- Some functions and data structures (esp. related to Windows programming) cannot be called/accessed from a thread other than the main UI thread; doing so may crash your program or cause an exception
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.
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
精彩评论