简体   繁体   English

C#并发和顺序-Dispatcher.BeginInvoke

[英]c# Concurrency and order - Dispatcher.BeginInvoke

I have a small problem: I got an object Log. 我有一个小问题:我有一个对象Log。 This object fires an event when it's write function is called. 该对象在调用write函数时会触发一个事件。 The write function is not necessary called on the current applications dispatcher. 当前应用程序调度程序上不需要调用write函数。 So assume the following code: 因此,假设以下代码:

protected void OnLoggingEnqueuedMessage(object sender, EnqueuedMessageEventArgs e)
{
    if (Application.Current.Dispatcher.CheckAccess())
        AddLogEntry(e.LogEntry);
    else
        Application.Current.Dispatcher.BeginInvoke(new Action(() => { AddLogEntry(e.LogEntry); }), null);
}

If Application.Current.Dispatcher.CheckAccess() returns false the order of items added can be messed up. 如果Application.Current.Dispatcher.CheckAccess()返回false,则添加的项目顺序可能会混乱。 I understand that operations enqueued with BeginInvoke are not necessary executed in the same order as BeginInvoke is called but how can i add the items in correct order? 我了解到,使用BeginInvoke排队的操作不必与调用BeginInvoke相同的顺序执行,但是我如何才能以正确的顺序添加项目?

You said: 你说:

I understand that operations enqueued with BeginInvoke are not necessary executed in the same order as BeginInvoke 我了解,使用BeginInvoke排队的操作不必与BeginInvoke相同的顺序执行

however the documentation states 但是文档指出

If multiple BeginInvoke calls are made at the same DispatcherPriority, they will be executed in the order the calls were made. 如果在同一DispatcherPriority上进行了多个BeginInvoke调用,则将按照调用的顺序执行它们。

and as you are not specifying a DispatcherPriority your calls will have the same priority. 当您未指定DispatcherPriority时,您的呼叫将具有相同的优先级。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM