views:

58

answers:

3

I have a separate thread that listens for data. And on receiving some data it needs to access one of the windows in the app and set some fields for that window.

Right now when I use this it throws an exception(saying this threads cannot access as Windows1 is owned by other thread):

        foreach (Window w in App.Current.Windows)
        {
            if (w.Name == "WindowIamInterested")
            {
                //w.SetField set some fields in the window and 
                //and do w.Show() or w.Activate() to show the window to user
            }
        }

The above code runs in a separate thread and not the main thread. Is there a way I can access and modify the window.

+2  A: 

Hi VNarasimhaM,

Are you looking for window's dispatcher? You could get a dispatcher from window, and ask him to execute your code via Dispatcher.Invoke() or Dispatcher.BeginInvoke()...

Anvaka
+1  A: 

If you're working with a WPF control, you would use its dispatcher to schedule the update on the UI thread:

myControl.Dispatcher.BeginInvoke(
  System.Windows.Threading.DispatcherPriority.Normal
  , new System.Windows.Threading.DispatcherOperationCallback(delegate
  {                   
    // update control here
    return null;
  }), null);

You would use Invoke() if you need to block until the control updates, otherwise you should use BeginInvoke().

ebpower
But how do I access myControl. Here myControl is a window. So how can I access the window. It throws an exception if I try to access it.
VNarasimhaM
A: 

You can use Dispatcher.Invoke:

Application.Current.Dispatcher.Invoke(
   (ThreadStart)delegate
   {
      // do your UI work here
   });

Dispatcher.Invoke executes synchronously. If you want to execute asynchronously you can use Dispatcher.BeginInvoke.

John Myczek
that worked. Thanks!!!
VNarasimhaM