【发布时间】:2011-01-16 02:00:28
【问题描述】:
我试图推迟向我的主窗体添加控件,目的是加快它的开始时间。好吧,我在以下异常中运行:
跨线程操作无效: 从线程访问的控件“Form1” 除了它创建的线程 开。
我试图在一个较小的示例上简单地解决问题,但问题仍然存在。这是我的代码:
using System;
using System.Drawing;
using System.Threading;
using System.Windows.Forms;
namespace AddConrolFromAnotherThread {
public partial class Form1 : Form {
public Form1() {
InitializeComponent();
}
private void AddButton() {
if(this.InvokeRequired){
this.Invoke(new MethodInvoker(this.AddButton));
}
Random random = new Random(2);
Thread.Sleep(20);
Button button = new Button();
button.Size = new Size(50,50);
button.Location =
new Point(random.Next(this.Width),random.Next(this.Height));
this.Controls.Add(button);
}
private void buttonStart_Click(object sender, EventArgs e) {
Thread addControlThread =
new Thread(new ThreadStart(this.AddButton));
addControlThread.Start();
}
}
}
我确实使用了 Invoke 方法并检查了 InvokeRequiered 是否为真,但 InvokeRequiered 一直保持“真”。我真的不明白这一点。至少我会期待 StackOverflow 异常,因为这是一个递归调用。
那么,如果有人遇到类似的问题,请你告诉我我做错了什么?
【问题讨论】:
标签: c# invoke multithreading