替代使用上muticast委托

问题描述:

慢DynamicInvoke我有以下的基类的代码:替代使用上muticast委托

public static void InvokeExternal(Delegate d, object param, object sender) 
{ 
    if (d != null) 
    { 
     //Check each invocation target 
     foreach (Delegate dDelgate in d.GetInvocationList()) 
     { 
      if (dDelgate.Target != null && dDelgate.Target is System.ComponentModel.ISynchronizeInvoke 
       && ((System.ComponentModel.ISynchronizeInvoke)(dDelgate.Target)).InvokeRequired) 
      { 
       //If target is ISynchronizeInvoke and Invoke is required, invoke via ISynchronizeInvoke 
       ((System.ComponentModel.ISynchronizeInvoke)(dDelgate.Target)).Invoke(dDelgate, new object[] { sender, param }); 
      } 
      else 
      { 
       //Else invoke dynamically 
       dDelgate.DynamicInvoke(sender, param); 
      } 
     } 
    } 
} 

此代码示例是负责调用一个事件时,表示为多播委托,其中调用目标包括不关心跨线程的小类,还包括实现ISynchronizeInvoke的类,并且非常关注跨线程,如Windows窗体控件。

从理论上讲,这个片段工作得很好,没有发生错误。但是DynamicInvoke速度非常慢,并不是说它是目前应用程序的瓶颈。

那么,有没有我的问题:有没有什么办法可以加速这个小功能而不用功能上直接订阅事件?

所有事件/代表的签名是(object sender, EventArgs param)

+1

你可以将你的输入委托转换为一个已知的委托类型来调用它们吗? – Gabe

+0

在某些情况下给EventHandler,但很遗憾没有。 – Emiswelt

+0

请参阅此[问题](http://*.com/questions/4751799/using-multicastdelegate-as-parameter-while-avoiding-dynamicinvoke)。底线:你可以使用'动态',这也是非常快的。 – nawfal

如果dDelegate是一个已知的类型(即动作),你总是可以投给它,并直接调用它。

这样说,如果你在.NET3.5上,你可以使用表达式树来获得一些优化。我的示例使用.NET4中的并发字典,但可以用普通字典和锁取代。

这个想法如下:委托持有它调用的方法。对于被称为创建(使用表达式树)的每个唯一方法,调用该特定方法的编译委托。创建一个已编译的委托代价很高,这就是缓存它很重要的原因,但是一旦创建了已编译的委托,其速度与普通委托一样快。

在我的机器上,3,000,000个调用花费了1秒的时间与编译的委托和16秒的DynamicInvoke。

// Comment this line to use DynamicInvoke instead as a comparison 
#define USE_FAST_INVOKE 


namespace DynInvoke 
{ 
    using System; 
    using System.Collections.Concurrent; 
    using System.Linq.Expressions; 
    using System.Reflection; 

    static class Program 
    { 
     delegate void CachedMethodDelegate (object instance, object sender, EventArgs param); 

     readonly static ConcurrentDictionary<MethodInfo, CachedMethodDelegate> s_cachedMethods = 
      new ConcurrentDictionary<MethodInfo, CachedMethodDelegate>(); 

     public static void InvokeExternal(Delegate d, object sender, EventArgs param) 
     { 
      if (d != null) 
      { 
       //Check each invocation target    
       foreach (var dDelgate in d.GetInvocationList()) 
       { 
        if (
          dDelgate.Target != null 
         && dDelgate.Target is System.ComponentModel.ISynchronizeInvoke 
         && ((System.ComponentModel.ISynchronizeInvoke)(dDelgate.Target)).InvokeRequired 
         ) 
        { 
         //If target is ISynchronizeInvoke and Invoke is required, invoke via ISynchronizeInvoke      
         ((System.ComponentModel.ISynchronizeInvoke)(dDelgate.Target)).Invoke(dDelgate, new object[] { sender, param }); 
        } 
        else 
        { 
#if USE_FAST_INVOKE 
         var methodInfo = dDelgate.Method; 

         var del = s_cachedMethods.GetOrAdd (methodInfo, CreateDelegate); 

         del (dDelgate.Target, sender, param); 
#else 
         dDelgate.DynamicInvoke (sender, param); 
#endif 
        } 
       } 
      } 
     } 

     static CachedMethodDelegate CreateDelegate (MethodInfo methodInfo) 
     { 
      var instance = Expression.Parameter (typeof (object), "instance"); 
      var sender = Expression.Parameter (typeof (object), "sender"); 
      var parameter = Expression.Parameter (typeof (EventArgs), "parameter"); 

      var lambda = Expression.Lambda<CachedMethodDelegate>(
       Expression.Call (
        Expression.Convert (instance, methodInfo.DeclaringType), 
        methodInfo, 
        sender, 
        parameter 
        ), 
       instance, 
       sender, 
       parameter 
       ); 

      return lambda.Compile(); 
     } 

     class MyEventListener 
     { 
      public int Count; 

      public void Receive (object sender, EventArgs param) 
      { 
       ++Count; 
      } 
     } 

     class MyEventSource 
     { 
      public event Action<object, EventArgs> AnEvent; 

      public void InvokeAnEvent (EventArgs arg2) 
      { 
       InvokeExternal (AnEvent, this, arg2); 
      } 
     } 

     static void Main(string[] args) 
     { 

      var eventListener = new MyEventListener(); 
      var eventSource = new MyEventSource(); 

      eventSource.AnEvent += eventListener.Receive; 

      var eventArgs = new EventArgs(); 
      eventSource.InvokeAnEvent (eventArgs); 

      const int Count = 3000000; 

      var then = DateTime.Now; 

      for (var iter = 0; iter < Count; ++iter) 
      { 
       eventSource.InvokeAnEvent (eventArgs); 
      } 

      var diff = DateTime.Now - then; 

      Console.WriteLine (
       "{0} calls took {1:0.00} seconds (listener received {2} calls)", 
       Count, 
       diff.TotalSeconds, 
       eventListener.Count 
       ); 

      Console.ReadKey(); 
     } 
    } 
} 

编辑:OP使用.NET2我补充说,应与.NET2运行兼容为例(因为我用VS2010我可能会错误地使用一些新的语言功能,但我没有编译使用.NET2运行时)。

// Comment this line to use DynamicInvoke instead as a comparison 
#define USE_FASTER_INVOKE 

namespace DynInvoke 
{ 
    using System; 
    using System.Globalization; 
    using System.Reflection.Emit; 
    using System.Collections.Generic; 
    using System.ComponentModel; 
    using System.Reflection; 

    static class FasterInvoke 
    { 
     delegate void CachedMethodDelegate (object instance, object sender, EventArgs param); 

     readonly static Dictionary<MethodInfo, CachedMethodDelegate> s_cachedMethods = 
      new Dictionary<MethodInfo, CachedMethodDelegate>(); 

     public static void InvokeExternal (Delegate d, object sender, EventArgs param) 
     { 
      if (d != null) 
      { 
       Delegate[] invocationList = d.GetInvocationList(); 
       foreach (Delegate subDelegate in invocationList) 
       { 
        object target = subDelegate.Target; 
        if (
         target != null 
         && target is ISynchronizeInvoke 
         && ((ISynchronizeInvoke)target).InvokeRequired 
         ) 
        { 
         ((ISynchronizeInvoke)target).Invoke (subDelegate, new[] { sender, param }); 
        } 
        else 
        { 
#if USE_FASTER_INVOKE 
         MethodInfo methodInfo = subDelegate.Method; 

         CachedMethodDelegate cachedMethodDelegate; 
         bool result; 

         lock (s_cachedMethods) 
         { 
          result = s_cachedMethods.TryGetValue (methodInfo, out cachedMethodDelegate); 
         } 

         if (!result) 
         { 
          cachedMethodDelegate = CreateDelegate (methodInfo); 
          lock (s_cachedMethods) 
          { 
           s_cachedMethods[methodInfo] = cachedMethodDelegate; 
          } 
         } 

         cachedMethodDelegate (target, sender, param); 
#else 
         subDelegate.DynamicInvoke (sender, param); 
#endif 
        } 
       } 
      } 
     } 

     static CachedMethodDelegate CreateDelegate (MethodInfo methodInfo) 
     { 
      if (!methodInfo.DeclaringType.IsClass) 
      { 
       throw CreateArgumentExceptionForMethodInfo (
        methodInfo, 
        "Declaring type must be class for method: {0}.{1}" 
        ); 
      } 


      if (methodInfo.ReturnType != typeof (void)) 
      { 
       throw CreateArgumentExceptionForMethodInfo (
        methodInfo, 
        "Method must return void: {0}.{1}" 
        ); 
      } 

      ParameterInfo[] parameters = methodInfo.GetParameters(); 
      if (parameters.Length != 2) 
      { 
       throw CreateArgumentExceptionForMethodInfo (
        methodInfo, 
        "Method must have exactly two parameters: {0}.{1}" 
        ); 
      } 


      if (parameters[0].ParameterType != typeof (object)) 
      { 
       throw CreateArgumentExceptionForMethodInfo (
        methodInfo, 
        "Method first parameter must be of type object: {0}.{1}" 
        ); 
      } 

      Type secondParameterType = parameters[1].ParameterType; 
      if (!typeof (EventArgs).IsAssignableFrom (secondParameterType)) 
      { 
       throw CreateArgumentExceptionForMethodInfo (
        methodInfo, 
        "Method second parameter must assignable to a variable of type EventArgs: {0}.{1}" 
        ); 
      } 

      // Below is equivalent to a method like this (if this was expressible in C#): 
      // void Invoke (object instance, object sender, EventArgs args) 
      // { 
      //  ((<%=methodInfo.DeclaringType%>)instance).<%=methodInfo.Name%> (
      //   sender, 
      //   (<%=secondParameterType%>)args 
      //   ); 
      // } 

      DynamicMethod dynamicMethod = new DynamicMethod (
       String.Format (
        CultureInfo.InvariantCulture, 
        "Run_{0}_{1}", 
        methodInfo.DeclaringType.Name, 
        methodInfo.Name 
        ), 
       null, 
       new[] 
        { 
         typeof (object), 
         typeof (object), 
         typeof (EventArgs) 
        }, 
       true 
       ); 

      ILGenerator ilGenerator = dynamicMethod.GetILGenerator(); 
      ilGenerator.Emit (OpCodes.Ldarg_0); 
      ilGenerator.Emit (OpCodes.Castclass, methodInfo.DeclaringType); 
      ilGenerator.Emit (OpCodes.Ldarg_1); 
      ilGenerator.Emit (OpCodes.Ldarg_2); 
      ilGenerator.Emit (OpCodes.Isinst, secondParameterType); 
      if (methodInfo.IsVirtual) 
      { 
       ilGenerator.EmitCall (OpCodes.Callvirt, methodInfo, null);     
      } 
      else 
      { 
       ilGenerator.EmitCall (OpCodes.Call, methodInfo, null);     
      } 
      ilGenerator.Emit (OpCodes.Ret); 

      return (CachedMethodDelegate)dynamicMethod.CreateDelegate (typeof (CachedMethodDelegate)); 
     } 

     static Exception CreateArgumentExceptionForMethodInfo (
      MethodInfo methodInfo, 
      string message 
      ) 
     { 
      return new ArgumentException (
       String.Format (
        CultureInfo.InvariantCulture, 
        message, 
        methodInfo.DeclaringType.FullName, 
        methodInfo.Name 
        ), 
       "methodInfo" 
       ); 
     } 
    } 

    static class Program 
    { 
     class MyEventArgs : EventArgs 
     { 

     } 

     class MyEventListener 
     { 
      public int Count; 

      public void Receive (object sender, MyEventArgs param) 
      { 
       ++Count; 
      } 
     } 

     delegate void MyEventHandler (object sender, MyEventArgs args); 

     class MyEventSource 
     { 
      public event MyEventHandler AnEvent; 

      public void InvokeAnEvent (MyEventArgs arg2) 
      { 
       FasterInvoke.InvokeExternal (AnEvent, this, arg2); 
      } 
     } 

     static void Main (string[] args) 
     { 
      MyEventListener eventListener = new MyEventListener(); 
      MyEventSource eventSource = new MyEventSource(); 

      eventSource.AnEvent += eventListener.Receive; 

      MyEventArgs eventArgs = new MyEventArgs(); 
      eventSource.InvokeAnEvent (eventArgs); 

      const int count = 5000000; 

      DateTime then = DateTime.Now; 

      for (int iter = 0; iter < count; ++iter) 
      { 
       eventSource.InvokeAnEvent (eventArgs); 
      } 

      TimeSpan diff = DateTime.Now - then; 

      Console.WriteLine (
       "{0} calls took {1:0.00} seconds (listener received {2} calls)", 
       count, 
       diff.TotalSeconds, 
       eventListener.Count 
       ); 

      Console.ReadKey(); 
     } 
    } 
} 
+0

谢谢你的帮助。 我在.Net 2.0上,但我会尝试进入您的概念,也许切换到4.0。请给我一些时间来尝试一下。 :) – Emiswelt

+0

只是FYI Linq表达式树在.NET35中可用。上述技术在.NET2中也是可行的,但争论更加困难。 – FuleSnabel

+0

我有点好奇,事情是如何发生的。无论如何.NET2样本对你有帮助吗?我有一些关于如何在需要时进一步提高性能的想法。 – FuleSnabel

如果你有一组已知类型的,你可以检查他们的第一,只有恢复到DynamicInvoke,如果你不知道在编译时的类型。

// delegate is most likely to be EventHandler 
var e1 = dDelegate as EventHandler; 
if (e1 != null) 
    e1(sender, param); 
else 
{ 
    // might be DelegateType2 
    var d2 = dDelegate as DelegateType2; 
    if (d2 != null) 
     d2(sender, param); 
    else 
    { 
     // try DelegateType3 
     var d3 = dDelegate as DelegateType3; 
     if (d3 != null) 
      d3(sender, param); 
     else 
      // last resort 
      dDelgate.DynamicInvoke(sender, param); 
    } 
} 
+0

这是一个不错的主意,通过对FuleSnabel的解决方案进行修改,通过检查特定的目标类型并直接调用调用目标上的方法来进一步提升程序的内部工作。 – Emiswelt

查看我的书架FastDelegate.Net。它在建设上做代码生产,并且具有匹配的性能。