In the "old days" of Windows app development, using the PostMessage Windows API function to post messages to your own app was a great way to move the processing of a particular task out of the current stack context, while staying on the main thread and thereby avoiding the nuances of trying to execute a main thread task on another thread (which of course leads to the use of Invoke style methods to move processing back on to the main thread, etc.)
All you had to do was:
- Create a custom windows message with a numeric value greater than WM_USER
- Use PostMessage to broadcast that message to your self
- Add a handler to the main dialog window to handle messages for your custom WM_* message and take action on it
This allowed you to move processing out of thorny execution contexts, like deep within a deeply nested call stack perhaps with methods holding on to resource locks, etc., and instead, delay processing to a "cleaner" execution context.
For example, I really don't like doing much of anything inside a property setter/getter, especially for dependency properties, except saving or restoring a value. That and event handlers are two prime examples of execution contexts where I would like to delay a task associated with a particular event and pass it back to the main thread to be executed at the top level of main thread's execution context.
I want to do the same with my WPF/XAML app, but I want to use only managed code so I don't want to use Windows API calls, if possible, so I'm trying to avoid doing something like that show in the following two SO posts:
How to create C# Event to handle MFC Windows message from PostMessage()
What's the equivalent of PostMessage to self, for Windows Forms?
Is there a C# mechanism, idiom, etc. compatible with WPF/XAML managed code that accomplishes the same?. Is there a WPF/XAML managed code technique that does make use of the app's input queue like PostMessage does?
Note, although not an expert I've used C#'s Task.Run(), TaskFactory.StartNew(), Control.BeginInvoke(), async/await, etc. facilities many times. As I said, I'm looking for something that hopefully does not require creating a new thread or any other unusual coding gymnastics.