Snowy
Snowy

Reputation: 6132

Windows Forms with FileSystemWatcher not launching a child form

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?

Upvotes: 4

Views: 1214

Answers (1)

Igby Largeman
Igby Largeman

Reputation: 16747

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.

Upvotes: 5

Related Questions