How to simulate Control.Invoke() in two NON-UI threads
- Suppose there's a thread A which is a UI thread.
- Thread A creates another thread B which is a non UI th开发者_如何学Cread.
- When thread B wants to raise an event in thread A all it has to do is if(Form1.InvokeRequired) Form1.Invoke(same method) and call the event within that same method right?
Simple. But my question is what if you want to do the same thing if both A and B are non-ui threads? Theres no form object to call Invoke() from thread B.
If WinForms apps do it why isn't there a mechanism like that for Non-UI threads? Am I missing something? Is there a similar method to raise an event in one non-ui thread from another non-ui thread?
Thanks in advance.
P.S. The producer/consumer model answers are not the ones I'm looking for here.
In the first scenario, since thread B knows it isn't the UI thread, it might as well just call .Invoke(...)
.
When there are two non-UI threads, you are going to have to use some kind of message passing / queue. You can't just interrupt thread A to run the work; you must code thread A to (for example) check a queue for work, dequeue an item and execute it. Which is pretty much what winforms does, courtesy of the windows message loop. It doesn't matter if it isn't the answer you're looking for - it is what it is.
If there is no UI, there is no issue of cross threading. So simply call them from the thread. You may require some synchronization mechanism though.
精彩评论