【发布时间】:2016-05-27 17:54:33
【问题描述】:
在 winforms 应用程序中跨线程操作无效。据我所知,我们无法使用任何其他线程修改在 UI 线程中创建的控件。我们应该使用 Control.Invoke 方法委托任何此类修改。
我注意到一种不同的行为。我们可以修改其他线程的一些属性,但不是全部。查看下面的最小代码。
new Thread(() =>
{
pictureBox1.Image = new Bitmap("path-to-file"); // Works fine. Replaces the old picture with the new one.
}).Start();
new Thread(() =>
{
pictureBox1.Size = new Size(100, 100); // Throws error
}).Start();
new Thread(() => {
label1.BackColor = Color.Red; // Works fine. Changes the background color.
}).Start();
new Thread(() => {
label1.Text = "SomeText"; // Throws error
}).Start();
我看到了this post,它解释了当控件不在视图中时可能会发生这种情况。但就我而言,控件始终可见。
有人可以解释这种行为背后的原因吗?
【问题讨论】:
-
出于好奇,是不是每次都抛出同一个异常?
标签: c# multithreading winforms