Sleep(suspend) and Resuming windows form starts program on worker thread instead of main thread

孤者浪人 提交于 2019-12-22 12:53:41

问题


The windows form I am working on subscribes to Microsoft.Win32.SystemEvents.PowerModeChanged and on Suspend it runs the Close() method on the form. On Resume it runs the Run() function like it would on initial load. The problem is that when the computer is woken from sleep mode the PowerModeChanged event is triggered on a worker thread named ".Net SystemEvents" and when Run() is called it recreates the form on this worker thread instead of the main thread.

This form is a project I inherited from another developer and I am new to windows form programming. I am wondering if there is a better way to handle the sleep/wake process rather than closing the forms and recreating them on wake or a way to force the creation onto the main thread. Note: If I remove the code and have it do nothing when the computer is slept (suspended) and nothing when it wakes (resumes) then the program continues to work correctly (running on the main thread). Any help will be appreciated. Thanks all.


回答1:


Capture the UI thread SynchronizationContext in a static field, and Post() on it to go back to the UI thread.



来源:https://stackoverflow.com/questions/10608551/sleepsuspend-and-resuming-windows-form-starts-program-on-worker-thread-instead

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!