0

I have an init method in which I create a thread and a window is displayed This is my application code

public static SplashWindow _splashWindow;

        private static ManualResetEvent ResetSplashCreated;
        private static Thread SplashThread;

        public static void Init(SplashWindow splashWindow)
        {
            _splashWindow = splashWindow;
            ResetSplashCreated = new ManualResetEvent(false);

            SplashThread = new Thread(() => ShowSplash(_splashWindow));
            SplashThread.SetApartmentState(ApartmentState.STA);
            SplashThread.IsBackground = true;
            SplashThread.Name = "Splash Screen";
            SplashThread.Start();

            ResetSplashCreated.WaitOne();
        }

 public static void ShowSplash(SplashWindow splash)
        {
            splash.Show();

            ResetSplashCreated.Set();
            System.Windows.Threading.Dispatcher.Run();
        }

now when i call this code:

SplashHelper.Init(new anim());

I get an error in the splash.show(); line

System.InvalidOperationException: 'The calling thread cannot access this object because a different thread owns it.'
Atena
  • 109
  • 2
  • 9
  • 1
    WPF has a UI thread in which handles all UI-related calls such as opening windows, progressbars, etc. Why would you event want to achieve this? – jegtugado Sep 24 '20 at 13:04
  • 1
    The window **must** be shown in the same thread that owns it. This means either you give the thread that owns it a message-pump, or you make sure the thread that owns it already has a message-pump (e.g. create it in the main UI thread) and then use that thread's dispatcher to invoke your accessing code (the call to `Show()`) in that thread. See duplicates. You are creating the `Window` object in a different thread from where you use it. You should probably just skip the thread stuff and show it in the original thread. Use a background thread for whatever is currently blocking your main thread. – Peter Duniho Sep 24 '20 at 18:56

1 Answers1

3

You cannot create the window on one thread and Show() it on another.

You will have to both create the thread and call Show() in your ShowSplash method (or on the calling thread).

If you look at the source code of Show, you'll see that the first thing it does is to call a VerifyContextAndObjectState() method.

This method checks whether you are on the thread on which the window was originally created. If you are on another thread, it throws the InvalidOperationException that you are currently getting.

mm8
  • 163,881
  • 10
  • 57
  • 88