Is it possible that GUI event interrupts running code from the GUI thread to execute its own event handler method?
I have a weird behavior in my GUI code. If the user produces a lot of events in a short time, it h开发者_运维问答appens that a running event handler method gets interrupted by another event handler method. Since everything runs in the same thread (GUI thread) everything should run sequential and an interruption should not be possible, or do I misunderstand something?
Thanks for your advise, Eny
No, that doesn't happen. You are right in your understanding that the thread runs sequentially.
The GUI thread can be interrupted but only to run a different thread, it will not re-enter the GUI thread to handle another event. A thread only has one instruction pointer and thus can only be in one place in the code, it can not be interrupted by itself.
If you are experiencing something that look like the GUI thread is re-entered, the reason is something else.
The GUI thead can however "interrupt" itself by calling the Application.DoEvents
method.
You are correct, in a single threaded application, event should be run sequentially. There are a few exceptions:
An event is fired and calls the first event handler in its subscriber list. The event handler fires an event of its own, which calls other event handlers. In this case, it would appear that the event was interrupted, but it was not. When the original event handler completes, the next event handler in the list will be called.
An event handler calls the
Application.DoEvents()
method. This will suspend the current event and process any messages waiting in the message queue (which will usually fire events of their own), and when it has finished processing all messages, it will return to the event. A problem may occur whenApplication.DoEvents()
causes a recursive call to the event which called it, as a result of firing an event from one of the messages it processed.Event handlers may be executed on different threads. Some events are not fired on the UI thread, and may fire on their own thread. This could cause events to be fired out of order and interrupt each other on a thread contexts switch. Make sure that the events you consume are fired on the UI thread, and if not,
Control.Invoke()
them onto the UI thread. An example of an event that is fired on a separate thread, possibly without you being aware of it, is theSystem.Threading.Timer.Elapsed
event.
精彩评论