Quantcast
Channel: Windows Presentation Foundation (WPF) forum
Viewing all articles
Browse latest Browse all 18858

WPF threading problem

$
0
0

I have a Windows Form application that creates a WPF window in a speech command recognised event, upon the event being triggered the WPF window is created but not shown.

First of all when I tried to do this I get the exception that "The calling thread must be STA, because many UI components require this"

Therefore with the code that creates the WPF window I enclose it in:

Thread STAThread = new Thread(() => {
//create WPF window here
});

STAThread.SetApartmentState(ApartmentState.STA);
STAThread.Start();
STAThread.Join();                  


That gets rid of the exception but then when I go to show the WPF window from outside the command recognised event I get the:

"The calling thread cannot access the object because of different thread owns it", so I then tried various things like:

myDispatcher = Dispatcher.CurrentDispatcher;
myDispatcher.Invoke((Action)(() => {
...// Show the WPF window here
}));

Now that gets rid of that exception but the WPF window does not show!?!

I know it's a threading problem because if I run the code to creates the WPF window in a DispatcherTimer tick event and then run the code that shows the WPF window in another DispatcherTimer tick event then it all works perfectly.  When I try this with the dispatcherTimer tick events I don't need to add any of the code above.  So basically this tells me that the DispatcherTimer knows a lot more about threading than I do and I need to go away and get my head around what is going on.  However having done that I am kind of getting nowhere apart from bashing my head against a wall so am reluctantly going to take the easy way out (well hopefully) and ask one of you how to get the code to work without having to use DispatcherTimer tick events.  However an explanation in terms of the threading would be appreciated.  I know that WPF components need to be created in single threaded apartment threads and a bit more but obviously not enough.

Any help greatly appreciated.







Viewing all articles
Browse latest Browse all 18858

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>