Reputation: 147
I've got Listbox on main form, and i'd like to call method in second thread with access to listbox. Code:
class SecThreadOp
{
public Thread thr1;
private ListBox listb1= new ListBox();
public SecThreadOp(ListBox lb)
{
thr1 = new Thread(write);
listb1 = lb;
}
public void write()
{
if (listb1.InvokeRequired)
{
listb1.Invoke(new Action(write));
}
else
{
for (int i = 0; i < 20; i++)
{
listb1.Items.Add("testing");
Thread.Sleep(2000);
}
}
}
}
and in main form i ve got:
.........
SecThreadOp sc;
.........
sc = new SecThreadOp(this.listBox1);
.........
private void button1_Click(object sender, EventArgs e)
{
sc.thr1.Start();
}
Application suspend after click button, but i want to display 'test' in listbox async.
Thanks
Upvotes: 0
Views: 153
Reputation: 5689
It looks like you're just re-calling write() in your background thread. In your Invoke, I'm assuming you want to update the ListBox
on the UI thread. Do something like this:
listb1.Invoke((MethodInvoker)delegate { listb1.Items.Add("testing"); });
Upvotes: 1