Reputation: 23759
I have a strange problem with a Windows Forms event. To be exact, it's a KryptonHeaderGroup's ButtonSpec Click event, but it also happens with a plain vanilla System.Windows.Forms.Button
.
In the click event, the user interface is brought down (there's a label and a cancel button left), and then an expensive LINQ query is built from previous user input, compiled and then executed. There are Application.DoEvents()
calls in the foreach which actually executes the query (it's LINQ to objects, so it's lazy). This enables the user to press cancel, and after the DoEvents
, a cancel flag is tested and the foreach is cancelled, and some clean up happens. So far, so good.
However, when I press the Cancel button after the first few results come in (the label shows how many are already there), the whole Click event handler is restarted! After adding some traces, it seems that this happens before the previous handler returns. In other words, it happens in one of the DoEvents
calls. The button is, of course, not pressed again. It does not happen if the button is disabled in the event handler. But since the button is not pressed, it should not fire its Click event again, should it?
I'm baffled. Obviously the workaround is to disable the button, but I'd like to know what may be the actual problem here. Can the event handler be restarted if DoEvents
is called before the handler finishes? Is calling DoEvents
not recommended / allowed in event handlers? But then, since everything is an event handler in an event-driven application, you could never call it :)
Additional hints that may be required to answer this question:
DoEvents
call is made.I appreciate anything that would explain the behaviour, even if it's just speculation :)
Upvotes: 1
Views: 1334
Reputation: 3374
DoEvents will process GUI messages so it will allow any further clicks or messages to be processed. I would recommend you don't call it in an event handler and to be honest I'd avoid using it at all.
From MSDN: Calling this method can cause code to be re-entered if a message raises an event.
Long term:
If this is a long running query you want to look at running it on a background thread and disable the button. This is the general pattern for this type of activity.
Upvotes: 3