1

I haven't been able to figure this one out for NUnit yet. There was a similar question asked, here where this exception was being raised. The answer resolves usage with xUnit, and the asker reports that he got it working for MSTest. I have tried calling Dispatcher.CurrentDispatcher.InvokeShutdown(); in the [TearDown], [TestFixtureTearDown], and [Test] methods, and am still getting the exception.

A few more details about my implementation: I've created an InputBox class which extends System.Windows.Window. I made a static method, InputBox.Show(prompt) which executes the following code:

        var input = "";
        var t = new Thread(() =>
            {
                var inputBox = new InputBox(prompt);
                inputBox.ShowDialog();
                input = inputBox.Input;
            }) {IsBackground = true};
        t.SetApartmentState(ApartmentState.STA);
        t.Start();
        t.Join();
        return input;

Any ideas?

Community
  • 1
  • 1
jegan
  • 190
  • 1
  • 11
  • I don't see any `Dispatcher` in your code. Add `Dispatcher.Run()` as the last line in the thread. – Federico Berasategui Sep 20 '13 at 22:01
  • 1
    The code snippet isn't very helpful, it doesn't actually show a call to InvokeShutdown. WPF is *very* picky about threading. After this code completes, the STA thread is a dead Norwegian parrot. Don't try to stop it, it is resting at the bottom of the cage, pining for the fjords. NUnit certainly does make it harder to configure the test thread to be an STA thread. Covered by [this answer](http://stackoverflow.com/questions/2434067/how-to-run-unit-tests-in-stathread-mode) – Hans Passant Sep 20 '13 at 22:15

2 Answers2

1

Thanks for the ideas in the comments about Dispatcher calls. I changed my InputBox.Show method so it now looks like this, and it's working great. I don't have any Dispatcher calls in my unit tests and I'm not getting the exception.

    public static string Show(string prompt)
    {
        string input = null;
        var t = new Thread(() =>
        {
            Dispatcher.CurrentDispatcher.Invoke(DispatcherPriority.Normal, new Action(() =>
            {
                var inputBox = new InputBox(prompt);
                inputBox.ShowDialog();
                input = inputBox.Input;
            }));
            Dispatcher.CurrentDispatcher.InvokeShutdown();
        }) { IsBackground = true };
        t.SetApartmentState(ApartmentState.STA);
        t.Start();
        t.Join();
        return input;
    }
jegan
  • 190
  • 1
  • 11
  • Ran into this while running a progress bar (in its own window) and then opening a second window. Thanks. – Chris Aug 25 '17 at 16:05
0

Have you Tried [RequireMTA] (use intelissence to prove the correctness) attribute on top of your test method? ApartmentState.STA - is in my opinion the statement that gives you trouble

  • The thread has to be STA in order to create a window. WPF requires STA for GUI components. – jegan Sep 20 '13 at 22:39