可能重复:
如何从 C# 中的另一个线程更新 GUI?
如何从线程类更新我的 UI?无法从线程访问更新表单控件。我想根据每个特定线程的进度更新我的 UI。
class MyClass
{
public delegate void CountChangedEventHandler(int vCount, int vIndex);
public event CountChangedEventHandler CountChanged;
private int count;
private int index;
public MyClass(int index)
{
this.index = index;
}
public int Count
{
get { return this.count; }
set
{
this.count = value;
if (this.CountChanged != null)
this.CountChanged(value, this.index);
}
}
public void DoWork(object o)
{
for (int i = 0; i < 10000; i++)
{
this.Count = i;
}
}
}
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
for (int i = 0; i < 3; i++)
{
MyClass myCount = new MyClass(i);
myCount.CountChanged += new MyClass.CountChangedEventHandler(UpdateUI);
ListViewItem lvi = new ListViewItem();
lvi.Text = "Thread #" + i.ToString();
lvi.SubItems.Add("");
listView1.Items.Add(lvi);
ThreadPool.QueueUserWorkItem(new WaitCallback(myCount.DoWork));
}
}
private void UpdateUI (int index, int count)
{
listView1.Items[index].SubItems[0].Text = count.ToString();
}
}