How do I check a property value of the Main Thread from a Worker Thread?
I have some asynchronous operations being performed on the main thread of my application. I need a worker thread to poll the main thread periodically and check a value on the main开发者_如何转开发 thread.
How can I do this? Can I raise an event on the worker thread that the main thread is listening to? Bidirectional communication.
Thanks..
Another more "manual" way to accomplish what you're asking for here. Have the main thread check the value of interest and then send a reset event to the worker thread:
Look at ManualResetEvent (and AutoResetEvent, depending on your needs) in the threading libraries. These are very simple down-and-dirty mechanisms for signalling between a worker thread and the main thread.
Create a Timer/callback on the main thread that checks the value at a reasonable period. If the desired value is evaluated to true, set the event which sends a signal down to the worker thread.
If you are using WPF, you can have the worker thread call the WPF window's Dispatcher.Invoke method to get to data on the Main thread. If you are using WinForms, the form itself has an "Invoke" method, and you can check the "InvokeRequired" method to determine if the Invoke method should be called.
精彩评论