【问题标题】:C# Events: How to process event in a parallel mannerC# 事件:如何以并行方式处理事件
【发布时间】:2009-10-04 10:40:06
【问题描述】:

我有一个我想以并行方式处理的事件。我的想法是让每个回调都添加到 ThreadPool 中,让每个注册事件的方法都由 ThreadPool 处理。

我的试用代码如下所示:

Delegate[] delegates = myEvent.GetInvocationList();
IAsyncResult[] results = new IAsyncResult[ delegates.Count<Delegate>() ];

for ( int i = 0; i < delegates.Count<Delegate>(); i++ )
{
    IAsyncResult result = ( ( TestDelegate )delegates[ i ] ).BeginInvoke( "BeginInvoke/EndInvoke", null, null );
    results[ i ] = result;
}

for ( int i = 0; i < delegates.Length; i++ )
{
    ( ( TestDelegate )delegates[ i ] ).EndInvoke( results[ i ] );
}

这只是为了玩,因为我很好奇怎么做。我确信有更好的方法来做到这一点。 我不喜欢创建一个包含 lambda 的 WaitCallback 的 Func。此外,与直接调用委托相比,DynamicInvoke 相当慢。我怀疑这种处理事件的方式是否比顺序处理更快。

我的问题是:如何以并行方式处理事件,最好使用 ThreadPool?

由于我通常使用 Mono,.NET 4.0 或任务并行库都不是一个选项。

谢谢!

编辑: - 由于 Earwickers 的回答,更正了示例。 - 更新了试用代码

【问题讨论】:

  • 您应该确保也为每个 BeginInvoke 调用 EndInvoke,以避免资源泄漏。另见msdn.microsoft.com/en-us/magazine/cc164036.aspx#S3
  • 关于使用 AsyncWaitHandle 属性:msdn.microsoft.com/en-us/library/…“当您在用于进行异步方法调用的委托上调用 EndInvoke 时,等待句柄不会自动关闭。如果您释放对等待句柄,当垃圾收集回收等待句柄时释放系统资源。要在使用完等待句柄后立即释放系统资源,请调用 WaitHandle.Close 方法。哎哟。

标签: c# performance event-handling delegates parallel-processing


【解决方案1】:

我会选择使用 DynamicMethod (LCG) 和状态对象的方法,该对象携带参数并跟踪调用(以便您可以等待它们完成)。

代码: 应该这样做(虽然尚未经过全面测试,因此在某些情况下可能会引发一些令人讨厌的异常):

/// <summary>
/// Class for dynamic parallel invoking of a MulticastDelegate.
/// (C) 2009 Arsène von Wyss, avw@gmx.ch
/// No warranties of any kind, use at your own risk. Copyright notice must be kept in the source when re-used.
/// </summary>
public static class ParallelInvoke {
    private class ParallelInvokeContext<TDelegate> where TDelegate: class {
        private static readonly DynamicMethod invoker;
        private static readonly Type[] parameterTypes;

        static ParallelInvokeContext() {
            if (!typeof(Delegate).IsAssignableFrom(typeof(TDelegate))) {
                throw new InvalidOperationException("The TDelegate type must be a delegate");
            }
            Debug.Assert(monitor_enter != null, "Could not find the method Monitor.Enter()");
            Debug.Assert(monitor_pulse != null, "Could not find the method Monitor.Pulse()");
            Debug.Assert(monitor_exit != null, "Could not find the method Monitor.Exit()");
            FieldInfo parallelInvokeContext_activeCalls = typeof(ParallelInvokeContext<TDelegate>).GetField("activeCalls", BindingFlags.Instance|BindingFlags.NonPublic);
            Debug.Assert(parallelInvokeContext_activeCalls != null, "Could not find the private field ParallelInvokeContext.activeCalls");
            FieldInfo parallelInvokeContext_arguments = typeof(ParallelInvokeContext<TDelegate>).GetField("arguments", BindingFlags.Instance|BindingFlags.NonPublic);
            Debug.Assert(parallelInvokeContext_arguments != null, "Could not find the private field ParallelInvokeContext.arguments");
            MethodInfo delegate_invoke = typeof(TDelegate).GetMethod("Invoke", BindingFlags.Instance|BindingFlags.Public);
            Debug.Assert(delegate_invoke != null, string.Format("Could not find the method {0}.Invoke()", typeof(TDelegate).FullName));
            if (delegate_invoke.ReturnType != typeof(void)) {
                throw new InvalidOperationException("The TDelegate delegate must not have a return value");
            }
            ParameterInfo[] parameters = delegate_invoke.GetParameters();
            parameterTypes = new Type[parameters.Length];
            invoker = new DynamicMethod(string.Format("Invoker<{0}>", typeof(TDelegate).FullName), typeof(void), new[] {typeof(ParallelInvokeContext<TDelegate>), typeof(object)},
                                        typeof(ParallelInvokeContext<TDelegate>), true);
            ILGenerator il = invoker.GetILGenerator();
            LocalBuilder args = (parameters.Length > 2) ? il.DeclareLocal(typeof(object[])) : null;
            bool skipLoad = false;
            il.BeginExceptionBlock();
            il.Emit(OpCodes.Ldarg_1); // the delegate we are going to invoke
            if (args != null) {
                Debug.Assert(args.LocalIndex == 0);
                il.Emit(OpCodes.Ldarg_0);
                il.Emit(OpCodes.Ldfld, parallelInvokeContext_arguments);
                il.Emit(OpCodes.Dup);
                il.Emit(OpCodes.Stloc_0);
                skipLoad = true;
            }
            foreach (ParameterInfo parameter in parameters) {
                if (parameter.ParameterType.IsByRef) {
                    throw new InvalidOperationException("The TDelegate delegate must note have out or ref parameters");
                }
                parameterTypes[parameter.Position] = parameter.ParameterType;
                if (args == null) {
                    il.Emit(OpCodes.Ldarg_0);
                    il.Emit(OpCodes.Ldfld, parallelInvokeContext_arguments);
                } else if (skipLoad) {
                    skipLoad = false;
                } else {
                    il.Emit(OpCodes.Ldloc_0);
                }
                il.Emit(OpCodes.Ldc_I4, parameter.Position);
                il.Emit(OpCodes.Ldelem_Ref);
                if (parameter.ParameterType.IsValueType) {
                    il.Emit(OpCodes.Unbox_Any, parameter.ParameterType);
                }
            }
            il.Emit(OpCodes.Callvirt, delegate_invoke);
            il.BeginFinallyBlock();
            il.Emit(OpCodes.Ldarg_0);
            il.Emit(OpCodes.Call, monitor_enter);
            il.Emit(OpCodes.Ldarg_0);
            il.Emit(OpCodes.Dup);
            il.Emit(OpCodes.Ldfld, parallelInvokeContext_activeCalls);
            il.Emit(OpCodes.Ldc_I4_1);
            il.Emit(OpCodes.Sub);
            il.Emit(OpCodes.Dup);
            Label noPulse = il.DefineLabel();
            il.Emit(OpCodes.Brtrue, noPulse);
            il.Emit(OpCodes.Stfld, parallelInvokeContext_activeCalls);
            il.Emit(OpCodes.Ldarg_0);
            il.Emit(OpCodes.Call, monitor_pulse);
            Label exit = il.DefineLabel();
            il.Emit(OpCodes.Br, exit);
            il.MarkLabel(noPulse);
            il.Emit(OpCodes.Stfld, parallelInvokeContext_activeCalls);
            il.MarkLabel(exit);
            il.Emit(OpCodes.Ldarg_0);
            il.Emit(OpCodes.Call, monitor_exit);
            il.EndExceptionBlock();
            il.Emit(OpCodes.Ret);
        }

        [Conditional("DEBUG")]
        private static void VerifyArgumentsDebug(object[] args) {
            for (int i = 0; i < parameterTypes.Length; i++) {
                if (args[i] == null) {
                    if (parameterTypes[i].IsValueType) {
                        throw new ArgumentException(string.Format("The parameter {0} cannot be null, because it is a value type", i));
                    }
                } else if (!parameterTypes[i].IsAssignableFrom(args[i].GetType())) {
                    throw new ArgumentException(string.Format("The parameter {0} is not compatible", i));
                }
            }
        }

        private readonly object[] arguments;
        private readonly WaitCallback invokeCallback;
        private int activeCalls;

        public ParallelInvokeContext(object[] args) {
            if (parameterTypes.Length > 0) {
                if (args == null) {
                    throw new ArgumentNullException("args");
                }
                if (args.Length != parameterTypes.Length) {
                    throw new ArgumentException("The parameter count does not match");
                }
                VerifyArgumentsDebug(args);
                arguments = args;
            } else if ((args != null) && (args.Length > 0)) {
                throw new ArgumentException("This delegate does not expect any parameters");
            }
            invokeCallback = (WaitCallback)invoker.CreateDelegate(typeof(WaitCallback), this);
        }

        public void QueueInvoke(Delegate @delegate) {
            Debug.Assert(@delegate is TDelegate);
            activeCalls++;
            ThreadPool.QueueUserWorkItem(invokeCallback, @delegate);
        }
    }

    private static readonly MethodInfo monitor_enter;
    private static readonly MethodInfo monitor_exit;
    private static readonly MethodInfo monitor_pulse;

    static ParallelInvoke() {
        monitor_enter = typeof(Monitor).GetMethod("Enter", BindingFlags.Static|BindingFlags.Public, null, new[] {typeof(object)}, null);
        monitor_pulse = typeof(Monitor).GetMethod("Pulse", BindingFlags.Static|BindingFlags.Public, null, new[] {typeof(object)}, null);
        monitor_exit = typeof(Monitor).GetMethod("Exit", BindingFlags.Static|BindingFlags.Public, null, new[] {typeof(object)}, null);
    }

    public static void Invoke<TDelegate>(TDelegate @delegate) where TDelegate: class {
        Invoke(@delegate, null);
    }

    public static void Invoke<TDelegate>(TDelegate @delegate, params object[] args) where TDelegate: class {
        if (@delegate == null) {
            throw new ArgumentNullException("delegate");
        }
        ParallelInvokeContext<TDelegate> context = new ParallelInvokeContext<TDelegate>(args);
        lock (context) {
            foreach (Delegate invocationDelegate in ((Delegate)(object)@delegate).GetInvocationList()) {
                context.QueueInvoke(invocationDelegate);
            }
            Monitor.Wait(context);
        }
    }
}

用法:

ParallelInvoke.Invoke(yourDelegate, arguments);

注意事项:

  • 不处理事件处理程序中的异常(但 IL 代码有一个 finally 递减计数器,以便该方法正确结束),这可能会导致问题。也可以在 IL 代码中捕获和传输异常。

  • 不执行除继承之外的隐式转换(例如 int 到 double),并且会引发异常。

  • 使用的同步技术不分配操作系统等待句柄,这通常有利于性能。可以在 Joseph Albahari's page 上找到有关 Monitor 工作原理的说明。

  • 经过一些性能测试后,这种方法的扩展性似乎比任何对委托使用“本机”BeginInvoke/EndInvoke 调用的方法(至少在 MS CLR 中)都要好。

【讨论】:

  • 那会很有趣,期待你的样品。
  • 发布了一些代码,但我只做了一个快速测试。不过似乎有效。
  • 感谢您的代码!它似乎有效,而且很高兴它比阅读更容易使用;-) 我运行了一个小型性能测试,将您的代码与事件的直接调用进行比较,然后与我在问题中发布的方法进行比较。结果是......ParallelInvoke:86ms,直接调用:21ms,我的尝试:36ms。在几次运行之后,比例似乎保持不变。保留我的版本会有什么明显的问题吗?如果有人好奇,我可以提供我的测试代码。
  • 我的代码需要预热(两个静态构造函数,以及对动态生成的方法的第一次调用)才能正常运行,它是一个完全通用的解决方案,适用于任何委托和任何参数的数量,包括值类型和引用类型(虽然没有 byref 类型,因为这实际上没有意义)。我想不出它比任何 DynamicInvoke 解决方案都慢的真正原因,但这也可能取决于所使用的框架(Mono 与 MS CLR)。因此,如果您可以向我展示您的一些代码,我将有兴趣调查性能缓慢的原因。
  • 好的,所以我自己做了一些测试。即使是直接调用调用列表中的委托的 BeginInvoke/EndInvoke 所用的时间也是我的代码的两倍(不计算一次预热调用),这对我的代码没有任何进一步的优化,也没有 DynamicInvoke 或额外的“代理” " 方法(你的 Func)。我将使用此代码发布另一个答案,以便您自己进行比较。
【解决方案2】:

如果委托的类型已知,您可以直接调用他们的 BeginInvoke 并将 IAsyncResults 存储在一个数组中以等待并结束调用。请注意,您应该调用 EndInvoke 以 avoid potential resource leaks。该代码依赖于 EndInvoke 一直等到调用完成的事实,因此不需要 WaitAll(请注意,WaitAll has several issues 这样我会避免使用它)。

这是一个代码示例,同时也是不同方法的简单基准:

public static class MainClass {
    private delegate void TestDelegate(string x);

    private static void A(string x) {}

    private static void Invoke(TestDelegate test, string s) {
        Delegate[] delegates = test.GetInvocationList();
        IAsyncResult[] results = new IAsyncResult[delegates.Length];
        for (int i = 0; i < delegates.Length; i++) {
            results[i] = ((TestDelegate)delegates[i]).BeginInvoke("string", null, null);
        }
        for (int i = 0; i < delegates.Length; i++) {
            ((TestDelegate)delegates[i]).EndInvoke(results[i]);
        }
    }

    public static void Main(string[] args) {
        Console.WriteLine("Warm-up call");
        TestDelegate test = A;
        test += A;
        test += A;
        test += A;
        test += A;
        test += A;
        test += A;
        test += A;
        test += A;
        test += A; // 10 times in the invocation list
        ParallelInvoke.Invoke(test, "string"); // warm-up
        Stopwatch sw = new Stopwatch();
        GC.Collect();
        GC.WaitForPendingFinalizers();
        Console.WriteLine("Profiling calls");
        sw.Start();
        for (int i = 0; i < 100000; i++) {
            // ParallelInvoke.Invoke(test, "string"); // profiling ParallelInvoke
            Invoke(test, "string"); // profiling native BeginInvoke/EndInvoke
        }
        sw.Stop();
        Console.WriteLine("Done in {0} ms", sw.ElapsedMilliseconds);
        Console.ReadKey(true);
    }
}

在我非常旧的笔记本电脑上,BeginInvoke/EndInvoke 需要 95553 毫秒,而我的 ParallelInvoke 方法 (MS .NET 3.5) 需要 9038 毫秒。因此,与 ParallelInvoke 解决方案相比,这种方法的扩展性不是好。

【讨论】:

  • 有关 BeginInvoke/EndInvoke 性能问题的解释,请参阅:stackoverflow.com/questions/532791/…
  • 感谢您指出这一点 - 由于它的局限性,我无论如何都会驳回 WaitAll 方法!正如我已经说过的,我会尽快尝试你的测试代码。
  • 我运行我的代码时进行了预热和更长的测试运行,以便更好地进行比较。每次运行 100,000 次时,ParallelInvoke 耗时约 16 秒(15948 毫秒),而 Begin/EndInvoke 耗时约 19 秒(19149 毫秒)。因此,您的解决方案似乎要快得多,这就是为什么我将您的 ParallelInvoke 代码标记为正确答案的原因。再次感谢。
  • 不客气。您在哪个运行时运行测试,是 Mono 吗?因为在我的情况下,Begin/EndInvoke 的表现要差得多。另外请注意,我对 ParallelInvoke 做了一个小编辑,并引入了 invokeCallback 字段,这使得它在调用列表中有多个事件的情况下表现更好。因此,如果您使用旧代码进行测试,也许也可以进行此更改以获得更好的性能。
  • 不,我在 MS.NET 上运行它。我注意到,与 MS.NET 相比,在 Mono 下运行时,我对此代码的单元测试似乎运行得更快。
【解决方案3】:

您似乎在代码 sn-p 中执行了两次异步启动。

首先您在委托上调用 BeginInvoke - 这会将工作项排队,以便线程池将执行委托。

然后在该委托中,您使用 QueueUserWorkItem 来...排队另一个工作项,以便线程池将执行真正的委托。

这意味着当您从外部委托返回一个 IAsyncResult(因此是一个等待句柄)时,它将在第二个工作项已排队时发出完成信号,而不是在它完成执行时发出信号。

【讨论】:

  • 你是对的,一开始我没有 BeginInvoke 在那里,玩的时候它爬进来了。我会更正这个例子!
【解决方案4】:

您这样做是为了提高性能吗?

只有当它允许您让多个硬件并行工作时才会起作用,并且会花费您的进程切换开销。

【讨论】:

  • 这只是一个我很好奇的实验。性能测试确实表明,此处显示的两种并行方法都比标准串行方法多花费数百个时间。
猜你喜欢
  • 1970-01-01
  • 2015-12-09
  • 1970-01-01
  • 1970-01-01
  • 2019-05-04
  • 1970-01-01
  • 2011-01-07
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多