title: Constructor is not on the thread which owns the object
body: <p>I have a side-window that is opened when clicking a button on the main window. This side-window is created on a separate thread from the main window.</p>
  
  <p>When I click the button the <strong>first time, everything runs fine</strong>. Then I close the side-window. Now when I click the button a <strong>second time</strong>, it throws the <code>InvalidOperationException</code>.</p>
  
  <p>When the side-window is closed, it and the thread it runs on are discarded, and each time it is opened, an entirely new thread is created which creates an entirely new window. The exception is raised in the constructor of the lowest sub-element of the window (i.e. the first time a UI object is accessed in constructing the window).</p>
  
  <p>Here is what happens. The handler of the button click:</p>
  
  <pre><code>public partial class MainWindow : Window
  {
      private void OnVariableMonitoringButtonClick(object sender, RoutedEventArgs e)
      {
          if (monitoringWindow == null)
          {
              Cursor = Cursors.Wait;
              monitoringWindow = new MonitoringWindowWrapper();
              monitoringWindow.Loaded += OnMonitoringWindowLoaded;
              monitoringWindow.Closed += OnMonitoringWindowClosed;
              monitoringWindow.Start(); // &lt;---
          }
          else
          {
              monitoringWindow.Activate();
          }
          e.Handled = true;
      }
  
      void OnMonitoringWindowLoaded(object sender, EventArgs e)
      {
          Dispatcher.Invoke(new Action(() =&gt; Cursor = Cursors.Arrow));
      }
  
      void OnMonitoringWindowClosed(object sender, EventArgs e)
      {
          monitoringWindow = null;
          Dispatcher.Invoke(new Action(() =&gt; Cursor = Cursors.Arrow));
      }
  }
  </code></pre>
  
  <p>The <code>MonitoringWindowWrapper</code> class merely wraps the relevant methods of the <code>MonitoringWindow</code> class inside <code>Dispatcher</code> invocations to handle cross-thread calls.</p>
  
  <p>The code enters the <code>MonitoringWindowWrapper.Start()</code> method:</p>
  
  <pre><code>partial class MonitoringWindowWrapper
  {
      public void Start()
      {
          // Construct the window in a parallel thread
          Thread windowThread = new Thread(LoadMonitoringWindow);
          windowThread.Name = "Monitoring Window Thread";
          windowThread.IsBackground = true;
          windowThread.SetApartmentState(ApartmentState.STA);
          windowThread.Start(); // &lt;---
      }
  
      private void LoadMonitoringWindow()
      {
          try
          {
              // Construct and set up the window
              monitoringWindow = new MonitoringWindow(); // &lt;---
              monitoringWindow.Loaded += OnMonitoringWindowLoaded;
              monitoringWindow.Closed += OnMonitoringWindowClosed;
              monitoringWindow.Show();
  
              // Start window message pump on this thread
              System.Windows.Threading.Dispatcher.Run();
          }
          catch (Exception e)
          {
              // Catch any exceptions in this window to save the application from crashing
              ErrorMessasgeBox.Show(e.Message);
              if (Closed != null) Closed(this, new EventArgs());
          }
      }
  }
  </code></pre>
  
  <p>The code then enters the <code>MonitoringWindow.MonitoringWindow()</code> constructor and filters down to my lowest sub-element in the window:</p>
  
  <pre><code>public partial class MonitoringWindow : Window
  {
      public MonitoringWindow()
      {
          InitializeComponent(); // &lt;---
          // ...
      }
  }
  </code></pre>
  
  <p>All the way down to:</p>
  
  <pre><code>public partial class LineGraph : UserControl, IGraph, ISubGraph
  {
  
      public LineGraph()
      {
          InitializeComponent();
          Brush b = GraphUtilities.BackgroundGradient;
          Background = b; // EXCEPTION THROWN AT THIS LINE
          BorderBrush = GraphUtilities.Border;
      }
  }
  </code></pre>
  
  <p>The exception call stack may give some insight into where the exception is thrown:</p>
  
  <pre><code>System.InvalidOperationException was unhandled by user code
   HResult=-2146233079
   Message=The calling thread cannot access this object because a different thread owns it.
   Source=WindowsBase
   StackTrace:
      at System.Windows.Threading.Dispatcher.VerifyAccess()
      at System.Windows.Freezable.ReadPreamble()
      at System.Windows.Media.GradientStopCollection.OnInheritanceContextChangedCore(EventArgs args)
      at System.Windows.DependencyObject.OnInheritanceContextChanged(EventArgs args)
      at System.Windows.DependencyObject.OnInheritanceContextChanged(EventArgs args)
      at System.Windows.Freezable.AddInheritanceContext(DependencyObject context, DependencyProperty property)
      at System.Windows.DependencyObject.ProvideSelfAsInheritanceContext(DependencyObject doValue, DependencyProperty dp)
      at System.Windows.DependencyObject.ProvideSelfAsInheritanceContext(Object value, DependencyProperty dp)
      at System.Windows.DependencyObject.UpdateEffectiveValue(EntryIndex entryIndex, DependencyProperty dp, PropertyMetadata metadata, EffectiveValueEntry oldEntry, EffectiveValueEntry&amp; newEntry, Boolean coerceWithDeferredReference, Boolean coerceWithCurrentValue, OperationType operationType)
      at System.Windows.DependencyObject.SetValueCommon(DependencyProperty dp, Object value, PropertyMetadata metadata, Boolean coerceWithDeferredReference, Boolean coerceWithCurrentValue, OperationType operationType, Boolean isInternal)
      at System.Windows.DependencyObject.SetValue(DependencyProperty dp, Object value)
      at System.Windows.Controls.Control.set_Background(Brush value)
      at Graphing.LineGraph..ctor() in z:\Documents\Projects\Software\Serial\SerialWindows\Graphing\LineGraph\LineGraph.xaml.cs:line 28
      at System.RuntimeType.CreateInstanceDefaultCtor(Boolean publicOnly, Boolean skipCheckThis, Boolean fillCache, StackCrawlMark&amp; stackMark)
  </code></pre>
  
  <p>The only reasons that I can think of are following:<br>
  1. There is a property of an object created on another thread that is bound to the <code>Background</code> property of this <code>LineGraph</code> object? However there aren't any such bindings (at least explicitly) in my application, and if that was the case then why does it work the first time?<br>
  2. The <code>Background</code> property is somehow not owned by the <code>LineGraph</code> object? But this makes no sense.<br>
  3. The constructor is somehow not being executed on the thread that created the object which it is constructing? This again makes no sense, and the Visual Studio debugger says that it is operating on the "Monitoring Window Thread" thread.  </p>
  
  <p>How can I fix this problem? </p>
  
  <p>I could possibly use the <code>Dispatcher</code> to set the background, but that is extremely tedious for all the calls to UI elements in that class and all the others, and it is not actually fixing the cause of the problem.</p>
  
  <p>Thank you very much!</p>