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

前端 未结 3 1714
不思量自难忘°
不思量自难忘° 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:30

    No that will not work. Well, at least it will not work consistently. It might work for awhile, but eventually it will fail unpreditably and spectaculary. The general rule is that you cannot do anything to a Form or Control on any other thread than the one it was created on. In other words, they have thread affinity. What you really need to do is have the main UI thread create and modify the PictureBox by marshaling a message into it. This can be done by taking advantage of the ISynchronizeInvoke methods. All forms and controls implement this interface.

    public void ThreadMethod()
    {
      pnlCapturePicture.Invoke((Action)(() =>
      {
        PictureBox pb = new PictureBox(); 
        pnlCapturePicture.Controls.Add(pb); 
        pb.Dock = DockStyle.Fill; 
        pb.ImageLocation = photopath; 
      }));
    }
    

提交回复
热议问题