Windows Forms with FileSystemWatcher not launching a child form

Deadly 提交于 2019-12-23 12:19:20

问题


I have a simple C# 4.0 Windows Forms form that make an instance of a FileSystemWatcher which watches a directory. When a file is added, the proper event fires, and I do some stuff in another directory. Then I make an instance of a child form. The child form hangs, and controls do not paint.

I think this is because the FileSystemWatcher is on a different thread, even though it looks like I am launching from the main form. What is the proper way to call a child form from a FileSystemWatcher event on what I think is another thread?


回答1:


Set the FileSystemWatcher.SynchronizingObject property to your main form.

MSDN:

When SynchronizingObject is null, methods handling the Changed, Created, Deleted, and Renamed events are called on a thread from the system thread pool. For more information on system thread pools, see ThreadPool.

When the Changed, Created, Deleted, and Renamed events are handled by a visual Windows Forms component, such as a Button, accessing the component through the system thread pool might not work, or may result in an exception. Avoid this by setting SynchronizingObject to a Windows Forms component, which causes the methods that handle the Changed, Created, Deleted, and Renamed events to be called on the same thread on which the component was created.



来源:https://stackoverflow.com/questions/6695944/windows-forms-with-filesystemwatcher-not-launching-a-child-form

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