当用户输入的当前处理完成时,有没有办法安排方法调用?某些喜欢将用户消息发布到消息队列。
让我们来看看如何处理用户输入:
1. User taps the screen | User input
2. Operating system puts a message in message queue | Operating system
3. WPF internals pick up the message \
4. WPF internals processes the message | WPF internals
5. WPF causes parts of application code to be run: /
a) As immediate reactions on events \ This is where call may
b) As an effect of dependency properties being changed / be scheduled
6. The application code finishes | Application code
7. The WPF internals finishes their work | WPF internals
*** This is where I want the scheduled method to run ***
8. WPF peeks for next message from message queue | WPF internals
我如何安排通话,以便在我想要的地方进行通话?
答案 0 :(得分:0)
如果我理解你的问题,那么我就是这样解决的。
声明2个全局变量:
Action<object> gPostProcessingMethod = null;//it must be accessible to any of the methods
// that may decide to schedule post-processing of your message
object gDataForPostProcessing = null;//it will hold a data for post-processing (if any)
我假设你有一个循环在某个地方轮询你的消息队列。我们假设这是while
循环。然后它应该看起来像这样来处理你的消息的后处理:
while (...)
{
// 1. Your code to dequeue/get next message:
// .................................
gPostProcessingMethod= null;
gDataForPostProcessing = null;
/* 2. Your code that triggers processing of the message. As far as I understand,
this triggering method does not return until all of the subsequently called
methods are done.
However, as you described, any of those methods may decide to schedule
"post-processing" method that must start at the moment the processing is complete.
This is how the scheduling should be done:
gPostProcessingMethod = <AnyMethodThatCompliesWithSignatureOfAction>
gDataForPostProcessing = ...;
*/
if (gPostProcessingMethod != null)
{//You mentioned that this call MUST happen synchronously (otherwise you may use ThreadPool, etc.)
gPostProcessingMethod(gDataForPostProcessing);
}
// 3. Your remaining code in the loop:
// ......................................
}
由于每个后续处理方法都可以覆盖先前分配给gPostProcessingMethod
和gDataForPostProcessing
的值,因此您应该接受下游方法具有优先级或相反:禁止更改这些变量(如果有)已经确定。
答案 1 :(得分:0)
有很多方法可以完成这项工作。我个人倾向于实施此类行为是使用ConcurrentQueue<>
答案 2 :(得分:-1)
您可以使用信号量进行多线程处理, 或者当单线程只是一个在方法开始时增加的int并在方法结束时减少。你只需等到它回到零。