Reputation: 697
the problem is simple I have GUI c#/xaml app and I want to run GUI in one thread and some method ( infinite loop ) in another thread. And I need to modify element in GUI ( listbox ) from second thread. I tried create global variable and some other tips from web, but nothing run well.
now I have something like:
public delegate void InvokeDelegate(listdata Mujlist);
//in global scope
// and in Window class
public void UpdateList(listdata Mujlist)
{
mujlistbox.DataContext = Mujlist;
}
// and in the second thread this
object[] obj = new object[1];
obj[0] = Mujlist;
mujlistbox.BeginInvoke(new InvokeDelegate(UpdateList), obj);
this maybe do a job well, BUT I can't try this, because VS 2010 find error
Error 1 'System.Windows.Controls.ListBox' does not contain a definition for 'BeginInvoke' and no extension method 'BeginInvoke' accepting a first argument of type 'System.Windows.Controls.ListBox' could be found (are you missing a using directive or an assembly reference?) D:\..\MainWindows.xaml.cs 85 28 WPFChat
BUT System.Windows.Forms have this method, so I am confused with this.
So, question is How can I simply update a listbox in "GUI thread" from child thread?
Where do I mistakes? Is there better way how do this? How?
Upvotes: 2
Views: 996
Reputation: 564403
With WPF, you need to use the Dispatcher.BeginInvoke
method.
While ListBox
is a UIElement
, which doesn't contain a BeginInvoke
method, it does derive from DispatcherObject
. As such, it has a Dispatcher
property you can use to get access to the Dispatcher
:
mujlistbox.Dispatcher.BeginInvoke(new InvokeDelegate(UpdateList), obj);
Upvotes: 3