views:

76

answers:

2

Hello folk,

I have a weird behavior in my GUI code. If the user produces a lot of events in a short time, it happens 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

+2  A: 

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.

Guffa
The Application.DoEvents is a good hint, I have to search the code if this is used somewhere.
Enyra
Yes that was it, thanks.
Enyra
+1  A: 

You are correct, in a single threaded application, event should be run sequentially. There are a few exceptions:

  1. 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.

  2. 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 when Application.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.

  3. 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 the System.Threading.Timer.Elapsed event.

Allon Guralnek
There is no time or anything else, which could produce another thread and I already check that it really happens within the same thread an no event handler is called manually. But Application.DoEvents could be possible, I'm going to check it now.
Enyra