Пример #1
0
        public MethodInvoker( MethodInfo method )
        {
            m_Method = method;

            if ( method != null )
                m_MethodHandler = BaseMethodInvoker.GetMethodInvoker( method );

            m_MethodEmpty = (method == null) | (m_MethodHandler == null);
        }
Пример #2
0
 public static bool SafeInvoke(this Control control, InvokeHandler handler)
 {
     if (control.InvokeRequired)
     {
         control.Invoke(handler);
         return false;
     }
     return true;
 }
Пример #3
0
        public MethodInvoker( Type type, string methodname )
        {
            MethodInfo mi = type.GetMethod( methodname );

            if ( mi != null )
                m_MethodHandler = BaseMethodInvoker.GetMethodInvoker( mi );

            m_MethodEmpty = (mi == null) | (m_MethodHandler == null);
        }
Пример #4
0
		void BeginInvoke (InvokeHandler action, TimeSpan interval)
		{
			var timer = new DispatcherTimer ();
			timer.Interval = interval;
			timer.Tick += (object sender, EventArgs args) => {
				timer.Stop ();
				action ();
			};
			timer.Start ();
		}
        public PropertyAccessor( Type type, string propertyName )
        {
            m_Type = type;

            m_GetMethodHandler = BasePropertyAccessor.GetPropertyInvoker( m_Type, propertyName );
            m_SetMethodHandler = BasePropertyAccessor.SetPropertyInvoker( m_Type, propertyName );

            if ( m_GetMethodHandler == null || m_SetMethodHandler == null )
                m_PropertyEmpty = true;
        }
Пример #6
0
 public static void SafeInvoke(this Control control, InvokeHandler handler)
 {
     if (control.InvokeRequired)
     {
         control.Invoke(handler);
     }
     else
     {
         handler();
     }
 }
 /// <summary>
 /// 扩展项目下所有Control类,线程操作Invoke共用处理
 /// </summary>
 /// <param name="control"></param>
 /// <param name="handler"></param>
 public static void UIInvoke(this Control control, InvokeHandler handler)
 {
     if (control.InvokeRequired)//如果跨线程则使用委托调用方法
     {
         control.Invoke(handler);
     }
     else//否则直接调用方法
     {
         handler();
     }
 }
Пример #8
0
 /// <summary>
 /// Initializes a new instance of the <see cref="RunFrm"/> class.
 /// </summary>
 /// <param name="sStartType">启动类型,区别正常启动和重新刷新启动.</param>
 public RunFrm()
 {
     InitializeComponent();
     //this.Update();
     KEYID_DEFAULT = 100;
     //KEYID_DEFAULT_CHANGE = KEYID_DEFAULT + 1;
     KEYID_DEFAULT_ACTIVE = KEYID_DEFAULT + 2;
     KEYID_DEFAULT_SHOWINFO = KEYID_DEFAULT + 3;
     //TYPE_NORMAL = "NORMAL";
     //TYPE_RESTART = "RESTART";
     //m_sStartType = sStartType;
     DoInvoke = HandleInvoke;
 }
Пример #9
0
        private bool RunSourceOverrideHandler(string sourceOverrideHandler)
        {
            Source        source  = current_source as Source;
            InvokeHandler handler = source != null
                ? source.GetInheritedProperty <InvokeHandler> (sourceOverrideHandler)
                : null;

            if (handler != null)
            {
                handler();
                return(true);
            }

            return(false);
        }
Пример #10
0
		internal void BeginInvoke (InvokeHandler action, TimeSpan timeout)
		{
#if MONOTOUCH
			MonoTouch.Foundation.NSTimer timer = null;
			timer = MonoTouch.Foundation.NSTimer.CreateScheduledTimer (timeout, () =>
			{
				try {
					action ();
				} finally {
					timer.Dispose ();
				}
			});
#else
			BeginInvokeHandler (action, timeout);
#endif
		}
Пример #11
0
        private void CancelInvoke(string methodName, object obj)
        {
            if (string.IsNullOrEmpty(methodName) || obj == null)
            {
                return;
            }
            if (!IsInvoking(methodName, obj))
            {
                return;
            }
            var action = InvokeList.Where(p => (p.Key.action?.Target ?? null) == obj && (p.Key.action?.Method?.Name ?? string.Empty) == methodName).FirstOrDefault().Key;

            if (action != null)
            {
                InvokeHandler.CancelInvoke(action.sender, action.action);
            }
        }
        public PropertyAccessor( Type type, PropertyInfo property )
        {
            m_Type = type;
            m_Property = property;

            if ( property == null )
            {
                m_PropertyEmpty = true;
                return;
            }

            m_GetMethodHandler = BasePropertyAccessor.GetPropertyInvoker( m_Type, property );
            m_SetMethodHandler = BasePropertyAccessor.SetPropertyInvoker( m_Type, property );

            if ( m_GetMethodHandler == null || m_SetMethodHandler == null )
                m_PropertyEmpty = true;
        }
Пример #13
0
 public void Initialize()
 {
     this.OnEnableAgency();
     if (this.UseCover)
     {
         this.OnEnableCover();
     }
     AiManagerLoadBalancer.aiManagerLoadBalancer.Add(this);
     if (this.HTNAgency != null)
     {
         this.HTNAgency.OnEnableAgency();
         if (AiManager.ai_htn_use_agency_tick)
         {
             InvokeHandler.InvokeRepeating(this, new Action(this.HTNAgency.InvokedTick), 0f, 0.033f);
         }
     }
 }
Пример #14
0
            private void EndRound()
            {
                GodmodeEnabled = true;

                if (currentRound >= rounds)
                {
                    winners.AddRange(eventPlayers);
                    InvokeHandler.Invoke(this, EndEvent, 0.1f);
                }
                else
                {
                    InvokeHandler.Invoke(this, StartRound, Configuration.TimeBetweenRounds);
                    BroadcastToPlayers(GetMessage, "Notification.RoundStartsIn", Configuration.TimeBetweenRounds);

                    StartCoroutine(ResetPlayers());
                }
            }
    public string InvokeString()
    {
        StringBuilder       stringBuilder = new StringBuilder();
        List <InvokeAction> list          = Facepunch.Pool.GetList <InvokeAction>();

        InvokeHandler.FindInvokes(this, list);
        foreach (InvokeAction invokeAction in list)
        {
            if (stringBuilder.Length > 0)
            {
                stringBuilder.Append(", ");
            }
            stringBuilder.Append(invokeAction.action.Method.Name);
        }
        Facepunch.Pool.FreeList <InvokeAction>(ref list);
        return(stringBuilder.ToString());
    }
Пример #16
0
 /// <summary>非本线程安全访问控件
 /// </summary>
 /// <param name="control">The control.</param>
 /// <param name="handler">The handler.</param>
 /// <param name="async"> </param>
 public static void ThreadSafeInvoke(this UserControl control, InvokeHandler handler, bool async)
 {
     if (control.InvokeRequired)
     {
         if (async)
         {
             control.BeginInvoke(handler);
         }
         else
         {
             control.Invoke(handler);
         }
     }
     else
     {
         handler();
     }
 }
Пример #17
0
            public void StopToDie()
            {
                enabled = false;
                isDying = true;

                if (entity != null)
                {
                    entity.SetFlag(BaseEntity.Flags.Reserved1, false, false);
                    foreach (var wheel in entity.wheels)
                    {
                        wheel.wheelCollider.motorTorque = 0;
                        wheel.wheelCollider.brakeTorque = float.MaxValue;
                    }
                }

                EjectAllPlayers();
                InvokeHandler.Invoke(this, OnDeath, 5f);
            }
Пример #18
0
 public void RegisterMethod <T>(MethodInfo methodInfo, InvokeHandler <T> invoke)
 {
     for (int i = 0, t = clazz.methods.Length; i < t; ++i)
     {
         var method = clazz.methods[i];
         var tar    = method;
         if (tar is CachedMethodInfo)
         {
             method = (tar as CachedMethodInfo).method;
         }
         if (method == methodInfo)
         {
             FixedMethodInfo <T> fixedMethod = new FixedMethodInfo <T>(tar, invoke);
             clazz.methods[i] = fixedMethod;
             break;
         }
     }
 }
Пример #19
0
		void BeginInvoke (InvokeHandler action, TimeSpan interval)
		{
			DateTime dt = DateTime.UtcNow.Add (interval);
			lock (callbacks) {
				bool inserted = false;
				var data = new InvokeData () { Action = action, Time = dt };
				for (int i = 0; i < callbacks.Count; i++) {
					if (dt > callbacks [i].Time) {
						callbacks.Insert (i, data);
						inserted = true;
						break;
					}
				}
				if (!inserted)
					callbacks.Add (data);
				callback_event.Set ();
			}
		}
Пример #20
0
            internal void DropFlag(bool resetToBase)
            {
                primary.SetParent(null, true);

                if (FlagHolder != null)
                {
                    FlagHolder.IsCarryingFlag = false;
                    FlagHolder = null;
                }

                primary.UpdateNetworkGroup();
                primary.SendNetworkUpdate(BasePlayer.NetworkQueue.Update);

                if (resetToBase)
                {
                    InvokeHandler.Invoke(this, DroppedTimeExpired, captureTheFlagEvent.flagRespawnTime);
                }
            }
Пример #21
0
        public static void BlockingProxyToMain (InvokeHandler handler)
        {
            if (!InMainThread) {
                var reset_event = new System.Threading.ManualResetEvent (false);

                ProxyToMainHandler (delegate {
                    try {
                        handler ();
                    } finally {
                        reset_event.Set ();
                    }
                });

                reset_event.WaitOne ();
            } else {
                handler ();
            }
        }
Пример #22
0
 public void Initialize()
 {
     this.OnEnableAgency();
     if (this.UseCover)
     {
         this.OnEnableCover();
     }
     AiManagerLoadBalancer.aiManagerLoadBalancer.Add((ILoadBalanced)this);
     if (this.HTNAgency == null)
     {
         return;
     }
     this.HTNAgency.OnEnableAgency();
     if (!AiManager.ai_htn_use_agency_tick)
     {
         return;
     }
     InvokeHandler.InvokeRepeating((Behaviour)this, new Action(this.HTNAgency.InvokedTick), 0.0f, 0.033f);
 }
Пример #23
0
            private void ResetFlag()
            {
                if (FlagHolder != null)
                {
                    FlagHolder.IsCarryingFlag = false;
                    FlagHolder = null;
                }

                InvokeHandler.CancelInvoke(this, DroppedTimeExpired);

                primary.SetParent(null);

                tr.position = basePosition;

                primary.UpdateNetworkGroup();
                primary.SendNetworkUpdate(BasePlayer.NetworkQueue.Update);

                IsAtBase = true;
            }
Пример #24
0
        public PropertyAccessor(Type type, PropertyInfo property)
        {
            m_Type     = type;
            m_Property = property;

            if (property == null)
            {
                m_PropertyEmpty = true;
                return;
            }

            m_GetMethodHandler = BasePropertyAccessor.GetPropertyInvoker(m_Type, property);
            m_SetMethodHandler = BasePropertyAccessor.SetPropertyInvoker(m_Type, property);

            if (m_GetMethodHandler == null || m_SetMethodHandler == null)
            {
                m_PropertyEmpty = true;
            }
        }
Пример #25
0
        public ContextMethodInvoker(Type messageType, MethodInfo methodInfo)
        {
            var dynamicMethod = new DynamicMethod(string.Empty, typeof(IMessageSender),
                                                  new[]
            {
                typeof(ITransportMessageFactory), typeof(IPipelineFactory), typeof(ISubscriptionManager),
                typeof(TransportMessage), typeof(object), typeof(CancellationToken)
            }, typeof(IMessageSender).Module);

            var il = dynamicMethod.GetILGenerator();

            il.Emit(OpCodes.Ldarg_0);
            il.Emit(OpCodes.Ldarg_1);
            il.Emit(OpCodes.Ldarg_2);
            il.Emit(OpCodes.Ldarg_3);
            il.Emit(OpCodes.Ldarg_S, 4);
            il.Emit(OpCodes.Ldarg_S, 5);

            var contextType     = HandlerContextType.MakeGenericType(messageType);
            var constructorInfo = contextType.GetConstructor(new[]
            {
                typeof(ITransportMessageFactory), typeof(IPipelineFactory), typeof(ISubscriptionManager),
                typeof(TransportMessage), messageType, typeof(CancellationToken)
            });

            il.Emit(OpCodes.Newobj, constructorInfo);
            il.Emit(OpCodes.Ret);

            _constructorInvoker = (ConstructorInvokeHandler)dynamicMethod.CreateDelegate(typeof(ConstructorInvokeHandler));

            dynamicMethod = new DynamicMethod(string.Empty,
                                              typeof(void), new[] { typeof(object), typeof(IMessageSender) },
                                              typeof(IMessageSender).Module);

            il = dynamicMethod.GetILGenerator();
            il.Emit(OpCodes.Ldarg_0);
            il.Emit(OpCodes.Ldarg_1);

            il.EmitCall(OpCodes.Callvirt, methodInfo, null);
            il.Emit(OpCodes.Ret);

            _invoker = (InvokeHandler)dynamicMethod.CreateDelegate(typeof(InvokeHandler));
        }
Пример #26
0
 private void OnDisable()
 {
     if (Rust.Application.isQuitting)
     {
         return;
     }
     this.OnDisableAgency();
     if (this.UseCover)
     {
         this.OnDisableCover();
     }
     AiManagerLoadBalancer.aiManagerLoadBalancer.Remove(this);
     if (this.HTNAgency != null)
     {
         this.HTNAgency.OnDisableAgency();
         if (AiManager.ai_htn_use_agency_tick)
         {
             InvokeHandler.CancelInvoke(this, new Action(this.HTNAgency.InvokedTick));
         }
     }
 }
Пример #27
0
            internal override void OnEventPlayerDeath(EventManager.BaseEventPlayer victim, EventManager.BaseEventPlayer attacker = null, HitInfo info = null)
            {
                if (victim == null)
                {
                    return;
                }

                (victim as ChopperSurvivalPlayer).LivesRemaining -= 1;

                if (GetPlayersRemainingCount() == 0)
                {
                    victim.AddPlayerDeath(null);

                    InvokeHandler.Invoke(this, EndEvent, 0.1f);
                    return;
                }

                victim.OnPlayerDeath(attacker, Configuration.RespawnTime);

                base.OnEventPlayerDeath(victim, attacker);
            }
Пример #28
0
        public static void BlockingProxyToMain(InvokeHandler handler)
        {
            if (!InMainThread)
            {
                var reset_event = new ManualResetEvent(false);

                ProxyToMainHandler(delegate {
                    try {
                        handler();
                    } finally {
                        reset_event.Set();
                    }
                });

                reset_event.WaitOne();
            }
            else
            {
                handler();
            }
        }
Пример #29
0
            public ObserverMethodInvoker(IPipelineObserver pipelineObserver, Type pipelineEventType)
            {
                _pipelineObserver = pipelineObserver;
                var pipelineObserverType = pipelineObserver.GetType();

                var dynamicMethod = new DynamicMethod(string.Empty,
                                                      typeof(void), new[] { typeof(IPipelineObserver), typeof(IPipelineEvent) },
                                                      typeof(IPipelineEvent).Module);

                var il = dynamicMethod.GetILGenerator();

                il.Emit(OpCodes.Ldarg_0);
                il.Emit(OpCodes.Ldarg_1);

                var methodInfo = pipelineObserverType.GetMethod("Execute", new[] { pipelineEventType });

                il.EmitCall(OpCodes.Callvirt, methodInfo, null);
                il.Emit(OpCodes.Ret);

                _invoker = (InvokeHandler)dynamicMethod.CreateDelegate(typeof(InvokeHandler));
            }
Пример #30
0
        private void pingButton_Click(object sender, EventArgs e)
        {
            DataTable table = new DataTable();

            table.Columns.Add("IP", typeof(string));
            table.Columns.Add("延时", typeof(string));

            resultGridView.DataSource = table;


            string[]      iplist   = ipListTextbox.Text.Trim().Split('\n');
            List <string> timeouts = new List <string>();

            foreach (var ip in iplist)
            {
                //此处线程需要管理,判断所有线程终止后
                InvokeHandler callback = new InvokeHandler(AddRow);
                Thread        th       = new Thread(() => { Ping(table, ip, callback); });
                th.Start();
            }
        }
Пример #31
0
    protected void DoCycle()
    {
        if (this.target == null)
        {
            return;
        }
        float extrapolationTime      = this.target.GetExtrapolationTime();
        float interpolationDelay     = this.target.GetInterpolationDelay();
        float interpolationSmoothing = this.target.GetInterpolationSmoothing();

        TransformInterpolator.Segment segment = this.interpolator.Query(Time.time, interpolationDelay, extrapolationTime, interpolationSmoothing);
        if (segment.next.time < this.interpolator.last.time)
        {
            this.extrapolatedTime = Mathf.Max(this.extrapolatedTime - Time.deltaTime, 0f);
        }
        else
        {
            this.extrapolatedTime = Mathf.Min(this.extrapolatedTime + Time.deltaTime, extrapolationTime);
        }
        if (this.extrapolatedTime > 0f && extrapolationTime > 0f && interpolationSmoothing > 0f)
        {
            float single = Time.deltaTime / (this.extrapolatedTime / extrapolationTime * interpolationSmoothing);
            segment.tick.pos = Vector3.Lerp(this.target.GetNetworkPosition(), segment.tick.pos, single);
            segment.tick.rot = Quaternion.Slerp(this.target.GetNetworkRotation(), segment.tick.rot, single);
        }
        this.target.SetNetworkPosition(segment.tick.pos);
        this.target.SetNetworkRotation(segment.tick.rot);
        if (PositionLerp.DebugDraw)
        {
            this.target.DrawInterpolationState(segment, this.interpolator.list);
        }
        if (Time.time - this.lastClientTime > 10f)
        {
            if (this.idleDisable == null)
            {
                this.idleDisable = new Action(this.IdleDisable);
            }
            InvokeHandler.Invoke(this, this.idleDisable, 0f);
        }
    }
Пример #32
0
    public string InvokeString()
    {
        StringBuilder       stringBuilder = new StringBuilder();
        List <InvokeAction> list          = (List <InvokeAction>)Pool.GetList <InvokeAction>();

        InvokeHandler.FindInvokes((Behaviour)this, list);
        using (List <InvokeAction> .Enumerator enumerator = list.GetEnumerator())
        {
            while (enumerator.MoveNext())
            {
                InvokeAction current = enumerator.Current;
                if (stringBuilder.Length > 0)
                {
                    stringBuilder.Append(", ");
                }
                stringBuilder.Append(((Delegate)current.action).Method.Name);
            }
        }
        // ISSUE: cast to a reference type
        Pool.FreeList <InvokeAction>((List <M0>&) ref list);
        return(stringBuilder.ToString());
    }
Пример #33
0
            private void OnDeath()
            {
                isDieing = true;

                if (player != null)
                {
                    player.EnsureDismounted();
                }

                InvokeHandler.Invoke(this, () =>
                {
                    Effect.server.Run(heliExplosion, transform.position);
                    ins.NextTick(() =>
                    {
                        if (entity != null && !entity.IsDestroyed)
                        {
                            entity.DieInstantly();
                        }
                        Destroy(this);
                    });
                }, 5f);
            }
Пример #34
0
        static void Main(string[] args)
        {
            // 1. Direct call to method
            Console.WriteLine($"Increament Direct call {Increament(100)} ");
            // 2. To invoke method using delegate create an instance of delegate
            // type and pass method address to it
            InvokeHandler handler = new InvokeHandler(Increament);

            // Invoke the method by passing the parameter to the delegate instance
            Console.WriteLine($"Increament using Delegate {handler(100)}");

            // 3. Using the Bridge method execute the delegate
            InvokeHandler handler1 = new InvokeHandler(Increament);

            Bridge(handler1);

            // 4. Use the delegate to directly contain and hide implementation
            // Anonymous method
            // Directly compiled and executed in Binary
            InvokeHandler handler2 = delegate(int x) {
                return(x + 10);
            };

            Console.WriteLine("Anonymous methods C# 2.0");
            Bridge(handler2);
            Console.WriteLine();

            Console.WriteLine("Anonymous methods C# 2.0 with simpler syntax");
            Bridge(delegate(int x) { return(x + 100); });

            Console.WriteLine();

            Console.WriteLine("Lambda Expression C# 3.0");
            // x goes into the method and return x + 1200
            Bridge((x) => { return(x + 1200); });

            Console.ReadLine();
        }
Пример #35
0
 private void Awake()
 {
     entity = GetComponent <BaseEntity>();
     npc    = entity.GetComponent <BaseNpc>();
     npc.CancelInvoke(npc.TickAi);
     npc.SetAiFlag(BaseNpc.AiFlags.Sleeping, false);
     animalConfig              = GetAnimalSpeed(npc);
     npc._maxHealth            = animalConfig.health;
     npc.health                = animalConfig.health;
     instance.animalAI[entity] = this;
     type         = animalConfig.agressive ? AType.Aggressive : AType.Passive;
     originalType = type;
     state        = AIState.Walking;
     lastPosition = entity.transform.position;
     InvokeHandler.InvokeRepeating(this, UpdateAI, 0, updateRate);
     if (IsStucked())
     {
         DestroyAndKill();
     }
     if (config.SleepAtNight)
     {
         InvokeHandler.InvokeRepeating(this, CheckTime, updateRate, 10 + updateRate);
     }
 }
Пример #36
0
 private void FPSTimer()
 {
     ++this.frames;
     this.time += Time.get_unscaledDeltaTime();
     if ((double)this.time < 1.0)
     {
         return;
     }
     Performance.current.frameRate = this.frames;
     Performance.current.frameTime = (float)((double)this.time / (double)this.frames * 1000.0);
     Performance.frameRateHistory[Performance.cycles % (long)Performance.frameRateHistory.Length] = Performance.current.frameRate;
     Performance.frameTimeHistory[Performance.cycles % (long)Performance.frameTimeHistory.Length] = Performance.current.frameTime;
     Performance.current.frameRateAverage   = this.AverageFrameRate();
     Performance.current.frameTimeAverage   = this.AverageFrameTime();
     Performance.current.memoryUsageSystem  = (long)SystemInfoEx.systemMemoryUsed;
     Performance.current.memoryAllocations  = GC.GetTotalMemory(false) / 1048576L;
     Performance.current.memoryCollections  = (long)GC.CollectionCount(0);
     Performance.current.loadBalancerTasks  = (long)LoadBalancer.Count();
     Performance.current.invokeHandlerTasks = (long)InvokeHandler.Count();
     this.frames = 0;
     this.time   = 0.0f;
     ++Performance.cycles;
     Performance.report = Performance.current;
 }
Пример #37
0
 private void FPSTimer()
 {
     this.frames++;
     this.time += Time.unscaledDeltaTime;
     if (this.time < 1f)
     {
         return;
     }
     Performance.current.frameRate = this.frames;
     Performance.current.frameTime = this.time / (float)this.frames * 1000f;
     Performance.frameRateHistory[checked ((IntPtr)(Performance.cycles % (long)((int)Performance.frameRateHistory.Length)))] = Performance.current.frameRate;
     Performance.frameTimeHistory[checked ((IntPtr)(Performance.cycles % (long)((int)Performance.frameTimeHistory.Length)))] = Performance.current.frameTime;
     Performance.current.frameRateAverage   = this.AverageFrameRate();
     Performance.current.frameTimeAverage   = this.AverageFrameTime();
     Performance.current.memoryUsageSystem  = (long)SystemInfoEx.systemMemoryUsed;
     Performance.current.memoryAllocations  = GC.GetTotalMemory(false) / (long)1048576;
     Performance.current.memoryCollections  = (long)GC.CollectionCount(0);
     Performance.current.loadBalancerTasks  = (long)LoadBalancer.Count();
     Performance.current.invokeHandlerTasks = (long)InvokeHandler.Count();
     this.frames         = 0;
     this.time           = 0f;
     Performance.cycles += (long)1;
     Performance.report  = Performance.current;
 }
Пример #38
0
            internal override void OnEventPlayerDeath(EventManager.BaseEventPlayer victim, EventManager.BaseEventPlayer attacker = null, HitInfo info = null)
            {
                if (victim == null)
                {
                    return;
                }

                victim.OnPlayerDeath(attacker, Configuration.RespawnTime);

                if (attacker != null && victim != attacker)
                {
                    attacker.OnKilledPlayer(info);

                    if (Config.ScoreLimit > 0 && attacker.Kills >= Config.ScoreLimit)
                    {
                        winner = attacker;
                        InvokeHandler.Invoke(this, EndEvent, 0.1f);
                        return;
                    }
                }

                UpdateScoreboard();
                base.OnEventPlayerDeath(victim, attacker);
            }
Пример #39
0
 public static object InvokeMethod(InvokeHandler invoke, object target, params object[] paramters)
 {
     return invoke(target, paramters);
 }
        /// <summary>
        /// 创建方法的快速处理封装
        /// </summary>
        /// <param name="methodInfo"></param>
        /// <returns></returns>
        public static InvokeHandler Create(MethodInfo methodInfo)
        {
            if (methodInfo.DeclaringType == null)
            {
                throw new InvalidOperationException("methodInfo的类型为空。");
            }
            DynamicMethod dynamicMethod = new DynamicMethod(string.Empty,
                                                            typeof(object),
                                                            new[] { typeof(object), typeof(object[]) },
                                                            methodInfo.DeclaringType.Module);
            ILGenerator il = dynamicMethod.GetILGenerator();

            ParameterInfo[] ps         = methodInfo.GetParameters();
            Type[]          paramTypes = new Type[ps.Length];
            for (int i = 0; i < paramTypes.Length; i++)
            {
                if (ps[i].ParameterType.IsByRef)
                {
                    paramTypes[i] = ps[i].ParameterType.GetElementType();
                }
                else
                {
                    paramTypes[i] = ps[i].ParameterType;
                }
            }
            LocalBuilder[] locals = new LocalBuilder[paramTypes.Length];

            for (int i = 0; i < paramTypes.Length; i++)
            {
                locals[i] = il.DeclareLocal(paramTypes[i], true);
            }
            for (int i = 0; i < paramTypes.Length; i++)
            {
                il.Emit(OpCodes.Ldarg_1);
                EmitFastInt(il, i);
                il.Emit(OpCodes.Ldelem_Ref);
                EmitCastToReference(il, paramTypes[i]);
                il.Emit(OpCodes.Stloc, locals[i]);
            }
            if (!methodInfo.IsStatic)
            {
                il.Emit(OpCodes.Ldarg_0);
            }
            for (int i = 0; i < paramTypes.Length; i++)
            {
                il.Emit(ps[i].ParameterType.IsByRef ? OpCodes.Ldloca_S : OpCodes.Ldloc, locals[i]);
            }
            il.EmitCall(methodInfo.IsStatic ? OpCodes.Call : OpCodes.Callvirt, methodInfo, null);
            if (methodInfo.ReturnType == typeof(void))
            {
                il.Emit(OpCodes.Ldnull);
            }
            else
            {
                EmitBoxIfNeeded(il, methodInfo.ReturnType);
            }

            for (int i = 0; i < paramTypes.Length; i++)
            {
                if (ps[i].ParameterType.IsByRef)
                {
                    il.Emit(OpCodes.Ldarg_1);
                    EmitFastInt(il, i);
                    il.Emit(OpCodes.Ldloc, locals[i]);
                    if (locals[i].LocalType.IsValueType)
                    {
                        il.Emit(OpCodes.Box, locals[i].LocalType);
                    }
                    il.Emit(OpCodes.Stelem_Ref);
                }
            }

            il.Emit(OpCodes.Ret);
            InvokeHandler invoker = (InvokeHandler)dynamicMethod.CreateDelegate(typeof(InvokeHandler));

            return(invoker);
        }
Пример #41
0
 public static void ProxyToMain (InvokeHandler handler)
 {
     if (!InMainThread) {
         ProxyToMainHandler (handler);
     } else {
         handler ();
     }
 }
Пример #42
0
 public static void RunIdle(InvokeHandler handler)
 {
     GLib.Idle.Add (delegate { handler (); return false; });
 }
            public override void Shutdown()
            {
                InvokeHandler handler = () => Close();

                handler.BeginInvoke(null, null);
            }
Пример #44
0
 public static void SafeInvoke(this System.Windows.Forms.Control control, InvokeHandler handler)
 {
     if (control.InvokeRequired) control.Invoke(handler);
     else handler();
 }
Пример #45
0
		public void Enqueue (InvokeHandler action)
		{
			AsyncTestCase.Current.AddTask (() => { action (); return true; });
		}
Пример #46
0
 public static void RunIdle(InvokeHandler handler)
 {
     GLib.Idle.Add(delegate { handler(); return(false); });
 }
Пример #47
0
 public static void Invoke(InvokeHandler handler)
 {
     RunIdle(delegate { handler(); return(false); });
 }
Пример #48
0
 public static void Invoke (InvokeHandler handler)
 {
     RunIdle (delegate { handler (); return false; });
 }
Пример #49
0
 /// <summary>
 /// Enqueues the specified invoker.
 /// </summary>
 /// <param name="invoker">The invoker.</param>
 public void Enqueue(InvokeHandler invoker)
 {
     Enqueue(new BackgroundTask {Invoker = invoker});
 }
Пример #50
0
 /// <summary>
 /// Enqueues the specified invoker.
 /// </summary>
 /// <param name="invoker">The invoker.</param>
 /// <param name="dueAt">The due at.</param>
 public void Enqueue(InvokeHandler invoker, DateTime dueAt)
 {
     Enqueue(new BackgroundTask { Invoker = invoker }, dueAt);
 }
Пример #51
0
		internal void BeginInvoke (InvokeHandler action)
		{
			BeginInvoke (action, TimeSpan.FromMilliseconds (1));
		}
Пример #52
0
 public void ShouldThrowExceptionWhenConstructorArgumentIsNull()
 {
     _invokeHandler = new InvokeHandler(_container);
 }