简体   繁体   中英

Application.Exit raises `FormClosed` for all open forms from calling thread, generating invalid thread accesses

My routine to check for updates is run as a separate process. Exiting the application is required to update, so a dialog asks the user, when an update is found, if they want to exit now. f they do, the code (from the update thread) calls Application.Exit() .

However, if the FormClosed event of any form that needs to be closed needs to access its controls, an invalid cross-thread operation is detected (which sounds pretty logical).

How would you solve this problem?

Thanks,
CFP.

The problem is induced by your code that checks for the updates, it runs on the wrong thread. Calling Application.Exit() from any thread other than the main UI thread is lethal. Even the message box is troublesome, although you'd get away with it, the box can easily disappear behind another window.

Maybe it is easily fixable. If you use FileSystemWatcher then use its SynchronizingObject property. If you use a Timer then use System.Windows.Forms.Timer. Anyhoo, the generic solution is to use Control.BeginInvoke() to make the code that displays the message box and calls Exit run on the main thread.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM