PostMessage 的 C# 等价物是什么,用于在当前线程上执行代码,就在将来?
What's the C# equivalent of PostMessage for executing code on the current thread, just in the future?
我有一种情况,我在事件处理程序中,我需要更改某些状态信息。但是,当我还在处理程序中时更改是不安全的,因此我需要在退出后执行它。但是,它 必须在同一个线程上执行。它必须在未来发生,而不是现在。
现在回到 Win32 时代,您有两种选择可以将消息发送到 window:
SendMessage
,这意味着 'Process the message right now!',通常是因为您当时需要结果,或者...
PostMessage
,它只说“将消息添加到 Window 的队列,以便 运行-loop 可以接收它。
选项 2 等同于我所追求的:'posting'(安排)一些代码在将来的某个时间执行。
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.
那么 PostMessage
的 C#/WPF 等价物是什么,我不需要调用的结果,但它仍然必须在同一个线程上发生,并且在当前事件完全完成后的某个时间处理了吗?
如果我没理解错,那么你要的是
//Will work sync
SynchronizationContext.Current.Send(...);
//Will work async
SynchronizationContext.Current.Post(...);
方法分别。
也请看看这篇精彩的文章
https://blogs.msdn.microsoft.com/pfxteam/2012/06/15/executioncontext-vs-synchronizationcontext/
一种粗略但易于理解的方法是启用计时器,然后在计时器触发时执行您的工作。
我有一种情况,我在事件处理程序中,我需要更改某些状态信息。但是,当我还在处理程序中时更改是不安全的,因此我需要在退出后执行它。但是,它 必须在同一个线程上执行。它必须在未来发生,而不是现在。
现在回到 Win32 时代,您有两种选择可以将消息发送到 window:
SendMessage
,这意味着 'Process the message right now!',通常是因为您当时需要结果,或者...PostMessage
,它只说“将消息添加到 Window 的队列,以便 运行-loop 可以接收它。
选项 2 等同于我所追求的:'posting'(安排)一些代码在将来的某个时间执行。
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.
那么 PostMessage
的 C#/WPF 等价物是什么,我不需要调用的结果,但它仍然必须在同一个线程上发生,并且在当前事件完全完成后的某个时间处理了吗?
如果我没理解错,那么你要的是
//Will work sync
SynchronizationContext.Current.Send(...);
//Will work async
SynchronizationContext.Current.Post(...);
方法分别。
也请看看这篇精彩的文章 https://blogs.msdn.microsoft.com/pfxteam/2012/06/15/executioncontext-vs-synchronizationcontext/
一种粗略但易于理解的方法是启用计时器,然后在计时器触发时执行您的工作。