1

I'm using SharpAdbClient and I register an event called OnDeviceConnected which fires when a device is plugged in to the PC where my form is running on.

When a device is connected and this event is fired, I'm trying to set a PictureBox image like so:

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

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

    ...
}

This attempt throws this error:

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

I have no idea where this "other" thread came from, since it didn't came from me, BUT If I'm changing the PictureBox's BackgroundImage like so:

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

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

    ...
}

It works fine.

How can it be? What is the deal with this error? I know I can just solve it by using the BackgroundImage property, but I want to understand what throws this error...?

Liran Friedman
  • 4,027
  • 13
  • 53
  • 96

1 Answers1

1

You are accessing the winfom controls from other thread, try this :

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;
                    }
    }
Ali Ezzat Odeh
  • 2,093
  • 1
  • 17
  • 17
  • 1
    Well, this answer is fine but my issue was that I used a 3rd party Nuget and it seems that it uses a worker thread so my MainThread was still active, as I found out, so I wrapped it with a background worker of my own and user the Invoke method. [Control.Invoke is hanging](http://stackoverflow.com/questions/13078175/control-invoke-is-hanging) – Liran Friedman Mar 22 '17 at 12:13
  • Good to know that you discovered the issue. – Ali Ezzat Odeh Mar 22 '17 at 13:33