Search code examples
wpftimerwindowthreadpool

How to delay window closing in WPF


I try to delay close a window in my App.xaml.ca :

Window splash = new Window();
splash.Show();

Timer timer = new Timer(callback, null, 2000, Timeout.Infinite);

private void callback(object stateInfo)
{
  splash.Close();
}

It works fine, but the whole App is shutdowning. What am doing wrong here ?


Solution

  • Be sure to check that you timer callback is coming back on the main dispatcher thread. If not then you will likely be getting an exception when you try to close your window from a different thread.

    Use splash.Dispatcher.CheckAccess() to make sure you are on the right thread and if not then use splash.Dispatcher.BeginInvoke((Action) () => splash.Close() to dispatch the call onto the main thread.

    Check out this page for more