Wow, I can't believe how may people didn't bother reading the question.
Anyways, this is what I do.
- Create you "message" classes. This stores all the information you want to share.
- Create a Queue<T> for each thread. Use a SyncLock (C# lock) to read/write to it.
- When you want to talk to a thread, send it a message object with a copy of all the information it needs by adding the message to the queue.
- The worker thread can then read from the queue, reading and processing each message in order. When there are no messages, simply sleep.
Make sure that you don't share objects between the two threads. Once your GUI thread sticks a message in the Queue, the GUI thread no longer owns the message. It cannot hold a reference to the message, or you will get yourself into trouble.
This won't give you the best possible performance, but it will be good enough for most applications. And more importantly, it will make it much harder to make a mistake.
UPDATE: Don't use a SyncLock and Queue. Instead use a ConcurrentQueue, which will handle any locking automatically for you. You'll get better performance and are less likely to make a mistake.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…