[英]Async method in winforms doesn't works
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 谢谢
It looks like you're just re-calling write() in your background thread. 看来您只是在后台线程中重新调用write()。 In your Invoke, I'm assuming you want to update the
ListBox
on the UI thread. 在您的Invoke中,假设您要更新UI线程上的
ListBox
。 Do something like this: 做这样的事情:
listb1.Invoke((MethodInvoker)delegate { listb1.Items.Add("testing"); });
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.