Why can't you initialize it in another thread? I see two scenarios:
- Initialization is slow for reasons other than WPF, which are preloaded / precomputed in another thread before initiating initialization of the main WPF.
- WPF itself consumes 4 seconds of processor time (although these are really WTF processor time levels ...). If so, you can start another STA stream using your own message pump, which can display an independent user interface (such as a spinning wheel) until the main thread is loaded.
You can create βdialogsβ that implicitly create a new dispatcher and run in the background thread, or you can explicitly create your own dispatcher (= message).
To do this, I use the following method:
public static Dispatcher StartNewDispatcher(ThreadPriority cpuPriority = ThreadPriority.Normal) { using (var sem = new SemaphoreSlim(0)) { Dispatcher retval = null; var winThread = new Thread(() => { retval = Dispatcher.CurrentDispatcher; sem.Release(); Dispatcher.Run(); }) { IsBackground = true, Priority = cpuPriority }; winThread.SetApartmentState(ApartmentState.STA); winThread.Start(); sem.Wait(); return retval; } }
This gives you a real multi-threaded interface; but it also means that you cannot communicate with the data or in any other way directly interact between the two user interfaces: after all, WPF objects are thread bound.
Before you go this route, check to see if there are any slow components that you can preload using the profiler: option 1 (preloading heavy material before WPF init) is easier and cleaner.
source share