0

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.

When I click the button the first time, everything runs fine. Then I close the side-window. Now when I click the button a second time, it throws the InvalidOperationException.

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).

Here is what happens. The handler of the button click:

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(); // <---
        }
        else
        {
            monitoringWindow.Activate();
        }
        e.Handled = true;
    }

    void OnMonitoringWindowLoaded(object sender, EventArgs e)
    {
        Dispatcher.Invoke(new Action(() => Cursor = Cursors.Arrow));
    }

    void OnMonitoringWindowClosed(object sender, EventArgs e)
    {
        monitoringWindow = null;
        Dispatcher.Invoke(new Action(() => Cursor = Cursors.Arrow));
    }
}

The MonitoringWindowWrapper class merely wraps the relevant methods of the MonitoringWindow class inside Dispatcher invocations to handle cross-thread calls.

The code enters the MonitoringWindowWrapper.Start() method:

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(); // <---
    }

    private void LoadMonitoringWindow()
    {
        try
        {
            // Construct and set up the window
            monitoringWindow = new MonitoringWindow(); // <---
            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());
        }
    }
}

The code then enters the MonitoringWindow.MonitoringWindow() constructor and filters down to my lowest sub-element in the window:

public partial class MonitoringWindow : Window
{
    public MonitoringWindow()
    {
        InitializeComponent(); // <---
        // ...
    }
}

All the way down to:

public partial class LineGraph : UserControl, IGraph, ISubGraph
{

    public LineGraph()
    {
        InitializeComponent();
        Brush b = GraphUtilities.BackgroundGradient;
        Background = b; // EXCEPTION THROWN AT THIS LINE
        BorderBrush = GraphUtilities.Border;
    }
}

The exception call stack may give some insight into where the exception is thrown:

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& 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& stackMark)

The only reasons that I can think of are following:
1. There is a property of an object created on another thread that is bound to the Background property of this LineGraph 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?
2. The Background property is somehow not owned by the LineGraph object? But this makes no sense.
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.

How can I fix this problem?

I could possibly use the Dispatcher 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.

Thank you very much!

kprobst
  • 16,165
  • 5
  • 32
  • 53
Brett
  • 298
  • 2
  • 16

2 Answers2

2

I would guess that the culprit is GraphUtilities.BackgroundGradient, but you have not listed the GraphUtilities class. Brushes are freezable objects.

From Freezable Objects Overview on MSDN:

A frozen Freezable can also be shared across threads, while an unfrozen Freezable cannot.

So the first time you run, that brush is associated with the monitoring window thread. The next time you open that window, it is a new thread. You will have to call the Freeze method on the brush if you want to use it from that other thread.

Jeremy Rosenberg
  • 792
  • 6
  • 18
  • Thanks! I added a `static` constructor to the `GraphUtilities` class which calls `Freeze()` on all the `Brush` objects that it exposes. That fixes the problem! Thanks :) – Brett Jul 11 '12 at 20:54
1

It is a precondition of WPF that all UI resources be created on and owned by a single thread, the UI thread. Many many things depend on the validity of the assumption that this will be so. If you do not comply with this then all bets are off.

You do not need to create a wait indicator UI on a background thread in order to use it on a background thread. Large applications create all their UI on the main thread. Long running activities occur on background threads. When the time comes, control marshalls onto the UI thread for just long enough to update the UI.

I suggest you read this carefully before proceeding.


So you got the answer you wanted. The fact that something can be done does not make it a good idea. In software design, clever is rarely the same as smart.

Peter Wone
  • 17,965
  • 12
  • 82
  • 134
  • My understanding was that UI resources can exist on any thread, so long as it is in STA mode. The only other condition being that they can only be accessed by the thread that created it. For example, read here: http://blogs.msdn.com/b/dwayneneed/archive/2007/04/26/multithreaded-ui-hostvisual.aspx . The main reason for the separate thread is to avoid blocking the main UI while the side-window is loading, and show the user a busy cursor while waiting. This would appear to be quite common in large applications, so it must be possible. Thanks. – Brett Jul 10 '12 at 10:59