Winforms - 在picturebox图像属性上获得跨线程错误

时间:2017-03-19 14:31:39

标签: c# multithreading winforms

我正在使用SharpAdbClient并注册一个名为├── project │ ├── steps │ ├── classes.py │ └── .feature files 的事件,当设备插入运行我的表单的PC时会触发该事件。

当连接设备并触发此事件时,我试图像这样设置PictureBox图像:

OnDeviceConnected

此尝试会抛出此错误:

void OnDeviceConnected(object sender, DeviceDataEventArgs e)
{
    ...

    imgBootFlashState.Image = Properties.Resources.locked; // CRASHES
    helpBootState.Image = Properties.Resources.help_boot_flash_disabled; // CRASHES

    ...
}

我不知道这个"其他"线程来自,因为它不是来自我,但是如果我像这样更改PictureBox Cross-thread operation not valid: Control 'MainForm' accessed from a thread other than the thread it was created on.

BackgroundImage

工作正常。

怎么可能?这个错误有什么处理? 我知道我可以使用void OnDeviceConnected(object sender, DeviceDataEventArgs e) { ... imgBootFlashState.BackgroundImage = Properties.Resources.locked; // WORKS helpBootState.BackgroundImage = Properties.Resources.help_boot_flash_disabled; // WORKS ... } 属性来解决它,但我想了解是什么引发了这个错误......?

1 个答案:

答案 0 :(得分:1)

您正在从其他线程访问winfom控件,请尝试以下操作:

if (this.InvokeRequired)
                    {
                        this.Invoke(new Action(() =>
                        {
                           imgBootFlashState.Image = Properties.Resources.locked;
                           helpBootState.Image = Properties.Resources.help_boot_flash_disabled; 
                        }));
                    }
                    else
                    {
                        imgBootFlashState.Image = Properties.Resources.locked;
                        helpBootState.Image = Properties.Resources.help_boot_flash_disabled;
                    }
    }