C# Winforms-获取picturebox图像属性的跨线程错误
我正在使用并注册一个名为C# Winforms-获取picturebox图像属性的跨线程错误,c#,multithreading,winforms,C#,Multithreading,Winforms,我正在使用并注册一个名为OnDeviconnected的事件,当一个设备插入到运行我的表单的PC时,该事件将触发 当连接设备并触发此事件时,我尝试设置PictureBox映像,如下所示: void OnDeviceConnected(object sender, DeviceDataEventArgs e) { ... imgBootFlashState.Image = Properties.Resources.locked; // CRASHES helpBootSt
OnDeviconnected
的事件,当一个设备插入到运行我的表单的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的背景图像,就像这样:
void OnDeviceConnected(object sender, DeviceDataEventArgs e)
{
...
imgBootFlashState.BackgroundImage = Properties.Resources.locked; // WORKS
helpBootState.BackgroundImage = Properties.Resources.help_boot_flash_disabled; // WORKS
...
}
它很好用
怎么可能呢?如何处理这个错误?
我知道我可以通过使用BackgroundImage
属性来解决这个问题,但我想了解是什么引发了这个错误…?如果您是从其他线程访问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;
}
}
这个答案很好,但我的问题是,我使用了一个第三方Nuget,它似乎使用了一个工作线程,所以我的主线程仍然是活动的,正如我发现的,所以我用我自己的后台工作线程和用户Invoke方法将其包装起来。很高兴知道你发现了这个问题。