它是邪恶的更新从后台C#线程一个PictureBox? [英] Is it evil to update a pictureBox from a background C# thread?

查看:340
本文介绍了它是邪恶的更新从后台C#线程一个PictureBox?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

首先,下面的代码似乎是工作。
它从一个连续的字节流中提取JPEG图像并将其显示在PictureBox到达时,如果封装数据包的检验是正确的。
令人担忧的是,因为在PictureBox间歇GUI问题异步由RxThread更新。
用在这里确定的方法,也可能这个崩溃,它展示给客户?



 公共FormMain()
{
的InitializeComponent();
变种T1 =新主题(RxThread){=的IsBackground真实};
t1.Start();
}

私人无效RxThread()
{
,而(真)
{
... //验证传入流
无功负载=新的字节[payloadSize]
... //从流复制JPEG图像有效载荷
pictureBox.Image =新位图(新的MemoryStream(负载));
}
}


解决方案

我觉得到UI控件的所有访问应该从UI线程来完成。修改从一个不拥有标的手柄可能有不良影响的线程控制。在最好的情况下异常会被抛出,在最坏的情况下,一切似乎是所有权利,直到一些竞争条件发生(你可能会花很多时间试图复制它)。



使用 调用 方法,传递您的委托,将在UI线程上执行。


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

解决方案

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.

这篇关于它是邪恶的更新从后台C#线程一个PictureBox?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆