I have a situation where I'm inside an event handler, and I need to change certain state information. However, it's not safe to change while I'm still in the handler, hence I need to execute it after I've exited. It does have to execute on the same thread however. It just has to happen in the future, not right then.
Now back in the Win32 days, you had two choices to send messages to a window:
SendMessage
, which means 'Process the message right now!', usually because you needed the result right then, or...PostMessage
, which only said 'Add the message to the Window's queue so the run-loop can pick it up.Option 2 is the equivalent of what I'm after: 'posting' (scheduling) some code to be executed sometime in the future.
Note: Searching here for 'C# equivalent of PostMessage' gives you this seemingly-related question. However, as most questions about
PostMessage
are, they too are asking about background threads and getting notifications back on the main thread, which again is not what I'm asking. I'm specifically talking about the same thread, just not right now. Anyway, just trying to stave off duplicate votes since that seems like an exact match. It's not.
So what's the C#/WPF equivalent of PostMessage
where I don't need the result of the call, but it has to still happen on the same thread, and sometime after the current event has been fully handled?
If I understood correctly then what you are after is
//Will work sync
SynchronizationContext.Current.Send(...);
//Will work async
SynchronizationContext.Current.Post(...);
methods respectively.
Please have a look at this marvelous article as well https://blogs.msdn.microsoft.com/pfxteam/2012/06/15/executioncontext-vs-synchronizationcontext/