0
可能重复:
How to update GUI from another thread in C#?C# - 线程的形式
我有textBox1的1和TextBox形式。我需要一个额外线程的简单例子来填充textBox2,只是为了理解原理。到目前为止,我使用MessageBox来显示值,但我想使用textBox2来代替。这是我的代码:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Threading;
namespace Threads_example
{
public partial class Form1 : Form
{
Thread t = new Thread(t1);
internal static int x1 = 1;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
}
static void t1()
{
do
{
x1++;
MessageBox.Show("x1 - " + x1.ToString());
}
while(x1<10);
}
private void button1_Click(object sender, EventArgs e)
{
t.Start();
for (int x = 1; x < 100000; x++)
{
textBox1.Text = x.ToString();
textBox1.Refresh();
}
}
}
}
线程无法直接访问UI组件。你需要使用'Control.Invoke'。在这里或通过谷歌搜索应该显示很多例子。 – ChrisF 2012-01-15 17:38:18