Your BeginLoading method can be called more than once before it completes and therefore can create more than one wpf window. This ruined all kinds of links. Also do not interrupt the flow, let it decide. Here are two changes:
public void BeginLoading() { this.thread = new Thread(this.RunThread); this.thread.IsBackground = true; this.thread.SetApartmentState(ApartmentState.STA); this.thread.Start(); while (this.loadingWindow == null) { } // <--- Add this line } public void EndLoading() { if (this.loadingWindow != null) { this.loadingWindow.Dispatcher.BeginInvoke(DispatcherPriority.Normal, (Action)(() => { this.loadingWindow.Close(); })); while (!this.ThreadReadyToAbort) { }; } //this.thread.Abort(); // <-- Remove this line }
Also, if it's all just for a busy screen, I would say that there should be a better and safer way than this. For academic purposes, this is an interesting problem, but not production code, especially if some junior developer could understand this.
Edit: there is still a crash on my machine if I reduce the delay between repeated caldes to BeginLoading and EndLoading. This may be due to the way the wpf window closes asynchronously. I removed the Closed event handler and simply used the boolean flag, indicating whether the window isLoaded or not, and I did not see any problems with this:
public class LoadingManager2 { public LoadingManager2() { } public LoadingManager2(string LoadingText) { loadingText = LoadingText; } private string loadingText = "Please wait .."; private Thread thread; private MyWindow loadingWindow; private bool isLoaded = false; public void BeginLoading() { this.thread = new Thread(this.RunThread); this.thread.IsBackground = true; this.thread.SetApartmentState(ApartmentState.STA); this.thread.Start(); while (!this.isLoaded) { }; } public void RunThread() { this.loadingWindow = new MyWindow(); this.isLoaded = true; this.loadingWindow.ShowDialog(); } public void EndLoading() { this.loadingWindow.Dispatcher.BeginInvoke(DispatcherPriority.Normal, (Action)(() => { this.loadingWindow.Close(); this.isLoaded = false; })); while (this.isLoaded) { }; } }
source share