Jim
Jim

Reputation: 2828

Generic method for WPF Window in a Separate Thread

I am using the bellow code for showing WPF window in seperate thread, which is working find however I have a lot of windows so this code is kind of repetitive. Could someone suggest on how to make it generic by passing Windows etc)? Thx

  // Create a thread
Thread newWindowThread = new Thread(new ThreadStart( () =>
{
    SynchronizationContext.SetSynchronizationContext(
        new DispatcherSynchronizationContext(
            Dispatcher.CurrentDispatcher));

    Window1 tempWindow = new Window1();
    tempWindow.Closed += (s,e) => Dispatcher.CurrentDispatcher.BeginInvokeShutdown(DispatcherPriority.Background);

    tempWindow.Show();

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

newWindowThread.SetApartmentState(ApartmentState.STA);

newWindowThread.IsBackground = true;

newWindowThread.Start();

Upvotes: 0

Views: 271

Answers (1)

rducom
rducom

Reputation: 7320

So a possible refactoring could be :

public static class WindowHelper
{
    public static void CreateWindow<TWindow>(Action onClose = null)
        where TWindow : Window, new()
    {
        // Create a thread
        Thread newWindowThread = new Thread(new ThreadStart(() =>
        {
            SynchronizationContext.SetSynchronizationContext(
                new DispatcherSynchronizationContext(
                    Dispatcher.CurrentDispatcher));
            TWindow tempWindow = new TWindow();
            tempWindow.Closed += (s, e) => 
               { 
                  if(onClose != null)
                      onClose();
                  Dispatcher.CurrentDispatcher.BeginInvokeShutdown(DispatcherPriority.Backgroud);
               }; 
            tempWindow.Show();
            System.Windows.Threading.Dispatcher.Run();
        }));

        newWindowThread.SetApartmentState(ApartmentState.STA);
        newWindowThread.IsBackground = true;
        newWindowThread.Start();
    }
}

And you can call this method like :

WindowHelper.CreateWindow<Window1>();

or

WindowHelper.CreateWindow<Window1>(() => Console.WriteLine("Closed"));

Upvotes: 1

Related Questions