从后台 C# 线程更新 pictureBox 是邪恶的吗?
首先,下面的代码似乎可以工作。 它从连续字节流中提取 jpeg 图像,如果封装数据包校验和正确,则在图像到达时将其显示在图片框中。 值得关注的是间歇性的 GUI 问题,因为 pictureBox 是由 RxThread 异步更新的。 这里使用的方法是否正常,或者在向客户展示时可能会崩溃?
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));
}
}
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));
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我认为对 UI 控件的所有访问都应该从 UI 线程完成。从不拥有底层句柄的线程修改控制可能会产生不良影响。在最好的情况下,将会抛出异常,在最坏的情况下,一切似乎都很好,直到发生某种竞争条件(并且您可能会花费大量时间尝试复制它)。
使用 Invoke 方法,传递您的委托将在 UI 线程上执行。
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.
为什么不使用
Invoke
来更新PictureBox
?Why you don't use
Invoke
to update thePictureBox
?你确定这真的有效吗?我不明白为什么它不会引发
InvalidOperationException: (跨线程操作无效)
因为控件是从创建的线程以外的线程更新的。您应该通过在 UI 线程上调用的委托方法来更新 UI。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.