Is it evil to update a pictureBox from a C # background thread?

First of all, the code below works. It extracts jpeg images from a continuous stream of bytes and displays them in a pictureBox as they arrive if the encapsulating packet checksum is correct. The GUI issue is troubling since the pictureBox is asynchronously updated by RxThread. Is the OK method used here, or may it fail to show it to the client?

public FormMain() { InitializeComponent(); var t1 = new Thread(RxThread) { IsBackground = true }; t1.Start(); } private void RxThread() { while (true) { ... // validate incoming stream var payload = new Byte[payloadSize]; ... // copy jpeg image from stream to payload pictureBox.Image = new Bitmap(new MemoryStream(payload)); } } 
+2
source share
3 answers

I think that all access to user interface controls should be done from the user interface thread. Modifying control from a thread that does not own a base descriptor can have undesirable consequences. In the best case, an exception will be thrown, in the worst case, everything may seem all right until some race condition occurs (and you can spend a lot of time playing it again).

Use the Invoke method, passing in the delegate that will be executed in the user interface thread.

+4
source

Why aren't you using Invoke to update PictureBox ?

+3
source

Are you sure you even work at all? I don’t understand why it would not raise an InvalidOperationException: (Cross-thread operation not valid) , because the control is being updated from a thread other than the one that was created. You must update the interface through the delegate method, which is called in the user interface thread.

+2
source

All Articles