jacknad
jacknad

Reputation: 13739

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

First of all, the code below seems to be working. It extracts jpeg images from a continuous byte stream and displays them in a pictureBox as they arrive if the encapsulating packet checksum is correct. The concern is intermittent GUI problems since the pictureBox is asynchronously updated by RxThread. Is the method used here OK or might this crash while showing it to the customer?

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));
    }
}

Upvotes: 2

Views: 2641

Answers (3)

mohamede1945
mohamede1945

Reputation: 7198

Why you don't use Invoke to update the PictureBox?

Upvotes: 3

Ed Swangren
Ed Swangren

Reputation: 124722

Are you sure that even works at all? I don't see why it wouldn't raise a InvalidOperationException: (Cross-thread operation not valid) as the control is being updated from a thread other than the one which is was created on. You should update the UI via a delegate method that is invoked on the UI thread.

Upvotes: 2

Jakub Konecki
Jakub Konecki

Reputation: 46008

I think all access to UI controls should be done from UI thread. Modifying control from the thread that doesn't own the underlying handle may have undesirable effects. In the best case scenario the exception will be thrown, in the worst case everything may seem to be all right until some race condition happens (and you may spend lots of time trying to replicate it).

Use Invoke method, passing your delegate that will be executed on the UI thread.

Upvotes: 4

Related Questions