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:
- The LINQ query takes a long time initially before supplying first results, i.e. before the first
DoEvents
call is made. - The LINQ query runs in the GUI thread because it would not make sense to allow the user to access the rest application, because the access will interfere with the underlying API both the GUI and the LINQ query use.
- I know I should load the LINQ query into a separate app domain and execute it there, to be able to unload it. But there will only be few different queries run by a typical user, and the resulting assembly is cached (for the same query string).
- The problem no longer happens if I either have a break point enabled (sigh - Heisenberg, anyone?) or if I cancel later during the query.
I appreciate anything that would explain the behaviour, even if it's just speculation :)