Reputation: 578
I'm learning C# and just started to practice with thread concept. I can't update the Listbox to show the data actually from a different thread other than Main thread.
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>()
}
Which is wrong here? And to fix it, which part I should learn? Thread or Delegate or Lamda?
Upvotes: 0
Views: 886
Reputation:
In VB I like to do it this way (the concept should carry over to C# almost identically)
Here is how I like to update my UI from another thread. Imagine that "Sub Method" updates the UI and DoMethod is called from another thread. Note that in my case I was updating a listbox that was bound to an observable collection using a data template. In my code I have to call listbox.items.refresh to have the screen reflect my changes. I am really new to WPF and VB (Grumpy old C++ Win32/MFC guy) so this is probably the most horrible code ever.
NOTE - the ellipses (...) is the variable parameter list. I like to match it to my original subs parameter list.
Delegate Sub DelegateMethod(...)
Sub Method(...)
End Sub
Public Sub DoMethod(...)
Dim DM As DelegateMethod = AddressOf Method
Me.Dispatcher.Invoke(DM, ...)
End Sub
Upvotes: 0
Reputation: 342
In WinForms application cal:
public void dumpList()
{
if (this.InvokeRequired)
{
this.Invoke(new MethodInvoker(this.dumpList));
return;
}
ListBoxS.DataSource = sl.dump(); //Returns a List<string>()
}
If the control's Handle was created on a different thread than the calling thread, property InvokeRequired = true (othervise false)
Upvotes: 1