Slow Invoke,DynamicInvoke和Func<>

时间:2013-07-03 17:08:58

标签: c# reflection

我正在使用反射来使用WindowsAPICodePack函数Microsoft.WindowsAPICodePack.Taskbar.TaskbarProgressBarState.SetProgressValue 它有效,但速度很慢。通常它需要大约20-30毫秒,但是使用这种方法,一次呼叫增加到大约180-190毫秒 我听说calling a method by reflection is about 1000 times slower than calling it normally,所以我寻找一种方法来加快速度。

最初,我有这个:

//class constructor
asm = Assembly.LoadFrom("Microsoft.WindowsAPICodePack.Shell.dll");
type = asm.GetType("Microsoft.WindowsAPICodePack.Taskbar.TaskbarManager");
classInstance = System.Runtime.Serialization.FormatterServices.GetUninitializedObject(type);

progressBarValueMethod = type.GetMethod("SetProgressValue", new Type[2]{typeof(int), typeof(int)});

//class method
progressBarValueMethod.Invoke(classInstance, new object[2]{val * 10, max * 10});

我试图通过改变它来加速它:

//class contructor
progressBarValueMethod = type.GetMethod("SetProgressValue", new Type[2]{typeof(int), typeof(int)});

//class method
progressBarValueMethod.Invoke(classInstance, new object[2] { val * 10, max * 10 });

到此:

//class constructor
progressBarValueMethod = type.GetMethod("SetProgressValue", new Type[2]{typeof(int), typeof(int)});
progressBarStateMethodDelegate = Delegate.CreateDelegate(typeof(Func<int, int>), classInstance, progressBarValueMethod);

//class method
progressBarStateMethodDelegate.DynamicInvoke(new object[2] { val * 10, max * 10 });

但它不起作用。调用此方法仍然需要大约180毫秒 我找到了另一个解决方案,所以我再次更改了代码:

//class constructor
progressBarValueMethod = type.GetMethod("SetProgressValue", new Type[2]{typeof(int), typeof(int)});
delegateFunc = (Func<int, int>)Delegate.CreateDelegate(typeof(Func<int, int>), classInstance, progressBarValueMethod);

//class method
delegateFunc(val * 10, max * 10);

没有改变任何东西。稳定180毫秒。 是否有不同的加速方式? 顺便说一句,我使用的是.NET 2.0。

0 个答案:

没有答案
相关问题