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