Your FormClosing
event is waiting for the background thread to close before it lets the method end. Note that it will be running in the UI thread.
Your background thread is, in a loop, invoking a method in the UI thread and, since you use Invoke
rather than BeginInvoke
, it is waiting for that method to complete before continuing.
The UI is running the closing event, sitting there doing nothing. Since it's doing nothing, it can't process any of the other events in the message loop, including the one method that the background thread is waiting on.
Both threads are each waiting on each other, and no productive work is being done. This is the definition of a deadlock. It will sit that way forever.
Note that this is a race condition though; if you're lucky enough for the form to be closed after a given Invoke
call completes and before the flag is next checked (which is hard; it spends very little time between those operations) then your program won't deadlock.
As for how to fix it; that's hard to say. The whole example is somewhat contrived.
Perhaps you don't need to be invoking to the UI at all from the background worker; if you're not actually doing UI work, you probably shouldn't be doing this.
Do you really need to wait for the background worker to finish in your closing handler? It's possible that you do, but often you wouldn't.