Curious about WinForm Control Thread Safety After Adding a Control on a Seperate Thread

前端 未结 3 1740
不思量自难忘°
不思量自难忘° 2021-01-22 07:24

I have a FileSystemWatcher set to pick up an picture that will be dropped in a particular directory. The way I was handling it was to add a PictureBox in code that is docked in

3条回答
  •  感动是毒
    2021-01-22 08:10

    No, it will not work. All GUI code must be done on the appropriate user interface thread. The thread context is not checked all the time, so it's possible to write something like that which will work now but fail on a future .NET framework update.

    In your case FileSystemWatcher understands the ISynchronizeInvoke pattern, so just set its SynchronizingObject property to the form it works with. Note that if you put a FileSystemWatcher on a form using the designer, this property is set automatically.

提交回复
热议问题