Essentially, your problem is right here:
pictureBox1.Image = b;
pictureBox2.Image = b1;
this.Refresh();
These are UI interactions and the WinFroms model dictates that all UI operations must execute on the UI thread.
Fortunately, fixing the code is relatively easy. You need to queue a delegate to update the UI on the main thread using the
BeginInvoke(..)
method.
this.BeginInvoke((Action)delegate {
pictureBox1.Image = b;
pictureBox2.Image = b1;
});
When you want to execute code on the UI thread, you have two options:
-
synchronous: queue a delegate and wait for it to be fully executed (using the
Invoke(..)
method,
-
asynchronous: queue the delegate and resume processing immediately, without waiting for the delegate to finish executing (or event to start) (using the
BeginInvoke(..)
)
Which method you choose depends on your needs but in your case the asynchronous option is most likely the right one since you don't care about the result of updating the picture boxes, and you want to resume capturing as soon as possible.
Also, the
this.Refresh()
call is not necessary because once you update the picture boxes they will automatically refresh the UI.