Launching a WPF Window from a Class Library Project

I create a kind of “loading screen” that will be shown from the class library just before some heavy processing, and then it will disappear when the processing is complete. My problem is that no matter what I do, heavy processing seems to block the UI thread. I had to set methods with the [STAThread] attribute so that the window would actually be created. Then I show the window using:

 bw = new BusyWindow(); bw.Show(); 

And then just hide it with bw.Hide() when the processing is done. I created a task for processing, so it should work in a separate thread.? Is STAThread completely useless, of course?

Another code:

 var taskStart = Task.Factory.StartNew(() => ShowBusyWindow()); var taskProcess = taskStart.ContinueWith((antecedent) => GetInternal()); var taskEnd = taskProcess.ContinueWith((antecedent) => HideBusyWindow()); return taskProcess.Result; 

And ShowBusywindow

 public void ShowBusyWindow() { bw = new BusyWindow(); bw.Show(); } 

And HideBusyWindow:

 public void HideBusyWindow() { bw.Close(); } 

I should also mention that I'm trying to open this library for COM, so it can be run from some VB6 code. I do not know if this affects anything ...?

+4
source share
1 answer

So, the WPF window can be called from the class library or any other thread using the following method:

 thread = new Thread(() => { bw = new BusyWindow(); bw.Show(); bw.Closed += (s, e) => bw.Dispatcher.InvokeShutdown(); Dispatcher.Run(); }); thread.SetApartmentState(ApartmentState.STA); //thread.IsBackground = true; thread.Start(); 

You do not need IsBackground for this. The only need for it is to disable the thread manager when closing the window. This would create a "ghost stream" if it were not closed.

The condition of the apartment must obviously be set in the STA so that the Window can actually be created. According to this site, single-threaded WPF windows can be useful for very intensive windows with a user interface (many graphs, etc.).

To close the window, I simply call thread.Abort() . I don't think this is the cleanest way to do this, but it works for what I need.

+4
source

Source: https://habr.com/ru/post/1347234/


All Articles