Reputation: 15016
I've read several posts here and via references from google, but haven't come up with the proper solution.
I have an assembly that displays a dialog, but that dialog needs to be shown from the main thread. The caller could be a .NET application or native application.
Conceptually, it seems like I simply need to get the application's main thread ID, and then call System.Windows.Threading.Dispatcher.FromThread( main_thread_id_here)
to get the Dispatcher, and then call Invoke
to display my dialog from the main thread. However, I haven't been able to figure out how to get the main thread ID.
My next approach was to (following advice from another SO question) iterate over Process.GetCurrentProcess().Threads
, and get the thread ID of the ProcessThread
that was started first. But now that I have this ProcessThread
, I don't have a way to get the corresponding Thread
object. I figured that I could next get a list of all running .NET threads in the current process, and compare their thread IDs via GetHashCode
to determine which one is the main thread. I could then use FromThread
to get the Dispatcher
... but I haven't been able to find any information on retrieving anything but ProcessThreads
!
Does anyone have tips on how to solve this problem using either approach I have explained above, or maybe another approach? Please keep in mind that I don't have control over the calling application.
Upvotes: 1
Views: 2956
Reputation: 15413
Application.Current.Dispatcher.BeginInvoke(new Action(() =>
{
// Show dialog
}));
You could also grab the dispatcher from the Window.Dispatcher
property.
Upvotes: 2