2

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?

John Saunders
  • 160,644
  • 26
  • 247
  • 397
ThinkDeep
  • 519
  • 1
  • 4
  • 19
  • Unlike forum sites, we don't use "Thanks", or "Any help appreciated", or signatures on [so]. See "[Should 'Hi', 'thanks,' taglines, and salutations be removed from posts?](http://meta.stackexchange.com/questions/2950/should-hi-thanks-taglines-and-salutations-be-removed-from-posts). – John Saunders Oct 12 '12 at 19:13

2 Answers2

3

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);
Reed Copsey
  • 554,122
  • 78
  • 1,158
  • 1,373
0

Use a BackGroundWorker and implement your long running operation in BackGroundWorker.DoWork method. Add a handler for progress reporting and update your UI from the progress event. Much simpler.

Refer to the marked answer on this question

Community
  • 1
  • 1
swiftgp
  • 997
  • 1
  • 9
  • 17