我正在学习C#,刚开始练习线程概念。我无法更新列表框以实际显示来自除主线程之外的其他线程的数据。
private void DoThreadBtn_Click(object sender, EventArgs e)
{
ListBoxS.DataSource = sl.dump(); //This update the ListBox.
//t = new Thread(dumpList); //This don't update the Listbox
//t.Start();
}
TestForm.ListBoxTest.StringList sl = new ListBoxTest.StringList();
public void dumpList()
{
ListBoxS.DataSource = sl.dump(); //Returns a List<string>()
}
这里哪个错了?并解决它,我应该学习哪一部分?线程或代表或Lamda?
答案 0 :(得分:1)
在WinForms应用程序中:
public void dumpList()
{
if (this.InvokeRequired)
{
this.Invoke(new MethodInvoker(this.dumpList));
return;
}
ListBoxS.DataSource = sl.dump(); //Returns a List<string>()
}
如果控件的Handle是在与调用线程不同的线程上创建的,则属性InvokeRequired = true(othervise false)
答案 1 :(得分:0)
在VB中我喜欢这样做(概念应该延续到C#几乎相同)
以下是我喜欢从其他线程更新我的UI的方法。想象一下,“Sub Method”更新UI,并从另一个线程调用DoMethod。请注意,在我的情况下,我正在使用数据模板更新绑定到可观察集合的列表框。在我的代码中,我必须调用listbox.items.refresh让屏幕反映我的更改。我是WPF和VB(Grumpy旧C ++ Win32 / MFC人)的新手,所以这可能是有史以来最恐怖的代码。
注意 - 省略号(...)是变量参数列表。我喜欢将它与我原来的子参数列表相匹配。
Delegate Sub DelegateMethod(...)
Sub Method(...)
End Sub
Public Sub DoMethod(...)
Dim DM As DelegateMethod = AddressOf Method
Me.Dispatcher.Invoke(DM, ...)
End Sub