In C# what is the recommended way of passing data between 2 threads?

后端 未结 9 842
长发绾君心
长发绾君心 2020-12-08 01:36

I have my main GUI thread, and a second thread running inside it\'s own ApplicationContext (to keep it alive, even when there is no work to be done). I want to call a method

相关标签:
9条回答
  • 2020-12-08 02:03

    Wow, I can't believe how may people didn't bother reading the question.

    Anyways, this is what I do.

    1. Create you "message" classes. This stores all the information you want to share.
    2. Create a Queue<T> for each thread. Use a SyncLock (C# lock) to read/write to it.
    3. 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.
    4. 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.

    0 讨论(0)
  • 2020-12-08 02:06

    Dude, read Albahari's .Net threading free ebook. I'm connected to it by any means, so this is no plug. I've read it, had my coworkers read it, and i've used it many times.

    I would recommend creating a producer/consumer class, where you can start a single thread that waits (non blocking), enqueue tasks to its queue, and signal it to start working.

    just google for it.

    0 讨论(0)
  • 2020-12-08 02:06

    You can use events or as Grauenwolf said - a message cue. I wrap each of my thread as a management singleton, from there you can implement either easily. You could even do poor man public properties to flip bits.

    Also you could implement a state machine, and instead of pass messages each thread could monitor each other

    0 讨论(0)
提交回复
热议问题