In my WPF application, I communicate asynchronously with the server. The callback will therefore not be executed in the user interface thread, and since I need to do some WPF stuff there (create an InkPresenter object), I need it to run in the user interface thread. Well, actually the requirement is that it starts in a thread with STA apartment mode. I tried to create a new thread with STA mode, but the result was that the UI thread could not access InkPresenter because it was "the owner of another thread."
In the callback, I want to use a dispatcher to call my function requiring an STA. Does this sound like the right approach? I am doing it now, but still fail. In my callback function, I run the following function, which now tries to verify that the address function is running in the user interface thread.
private void UpdateAnnotationsForCurrentFrameCollection()
{
if (Dispatcher.CurrentDispatcher.CheckAccess())
{
DoSomethingIncludingInkPresenter();
}
else
{
Dispatcher.CurrentDispatcher.Invoke(DispatcherPriority.Normal,
new Action(DoSomethingIncludingInkPresenter));
}
}
private void DoSomethingIncludingInkPresenter()
{
var inkPresenter = XamlReader.Parse(_someXamlString) as InkPresenter;
}
As the example shows, I use CheckAccess () to make sure that I only call the function if it is not already running in the user interface thread. When my callback calls this function, CheckAccess () is always right, but Dispatcher.CurrentDispatcher.Thread.ApartmentStateit is MTA. What for? I tried to remove CheckAccess () and always do Invoke, but ApartmentState remains MTA, and the creation of InkPresenter fails.
- , ? - ? , - ?