Possible Duplicate:
How to update the GUI from another thread in C#?
How can I update my UI from a threaded class? Unable to access update form Controls from threads. I’d like to update my UI on the progress of each specific thread.
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();
}
}
You need to use
InvokeorBeginInvoketo marshal the UI access back to the UI thread.I recommend using
Invokein this instance as this will stop your loop getting too far ahead of itself: