【问题标题】:Winforms - getting Cross-thread error on picturebox image attributeWinforms - 在图片框图像属性上出现跨线程错误
【发布时间】:2017-08-10 19:06:44
【问题描述】:

我正在使用SharpAdbClient 并注册了一个名为OnDeviceConnected 的事件,该事件在设备插入运行我的表单的PC 时触发。

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

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

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

    ...
}

此尝试引发此错误:

Cross-thread operation not valid: Control 'MainForm' accessed from a thread 
other than the thread it was created on.

我不知道这个“其他”线程来自哪里,因为它不是来自我,但是如果我像这样更改 PictureBox 的 BackgroundImage

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

    imgBootFlashState.BackgroundImage = Properties.Resources.locked; // WORKS
    helpBootState.BackgroundImage = Properties.Resources.help_boot_flash_disabled; // WORKS

    ...
}

效果很好。

怎么可能?这个错误是怎么回事? 我知道我可以通过使用 BackgroundImage 属性来解决它,但我想了解是什么引发了这个错误......?

【问题讨论】:

    标签: c# multithreading winforms


    【解决方案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;
                        }
        }
    

    【讨论】:

    • 嗯,这个答案很好,但我的问题是我使用了第 3 方 Nuget,而且它似乎使用了一个工作线程,所以我的 MainThread 仍然处于活动状态,正如我发现的那样,所以我将它包装起来使用我自己的后台工作人员并使用 Invoke 方法。 Control.Invoke is hanging
    • 很高兴知道您发现了这个问题。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-22
    • 1970-01-01
    • 2017-11-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多