static void DisplayMulticastInfo(MulticastDelegate md) { foreach(var d in md.GetInvocationList()) { DisplayDelegateInfo(d); } }
internal void FireEventToDelegates(MulticastDelegate md, ManagementEventArgs args) { try { if (md != null) { Delegate[] invocationList = md.GetInvocationList(); for (int i = 0; i < (int)invocationList.Length; i++) { Delegate @delegate = invocationList[i]; try { object[] objArray = new object[2]; objArray[0] = this.sender; objArray[1] = args; @delegate.DynamicInvoke(objArray); } catch { } } } } catch { } }
/// <summary> /// Initializes the class with the given <paramref name="targetDelegate"/> /// </summary> /// <param name="targetDelegate">The delegate that will be used to instantiate the factory.</param> public DelegateFactory(MulticastDelegate targetDelegate) { if (targetDelegate.Method.ReturnType == typeof(void)) throw new ArgumentException("The factory delegate must have a return type."); _targetDelegate = targetDelegate; }
public static void InvokeMulticast(object sender, MulticastDelegate md) { if (md != null) { InvokeMulticast(sender, md, null); } }
public static void InvokeDelegates(MulticastDelegate mDelegate, object sender, EventArgs e) { if (mDelegate == null) return; Delegate[] delegates = mDelegate.GetInvocationList(); if (delegates == null) return; // Invoke delegates within their threads foreach (Delegate _delegate in delegates) { if (_delegate.Target.GetType().ContainsGenericParameters) { Console.WriteLine("Cannot invoke event handler on a generic type."); return; } object[] contextAndArgs = { sender, e }; ISynchronizeInvoke syncInvoke = _delegate.Target as ISynchronizeInvoke; { if (syncInvoke != null) { // This case applies to the situation when Delegate.Target is a // Control with an open window handle. syncInvoke.Invoke(_delegate, contextAndArgs); } else { _delegate.DynamicInvoke(contextAndArgs); } } } }
/// <summary> /// Remove the given delegate from my invocation list. /// </summary> protected override sealed Delegate Remove(Delegate other) { if (this.Equals(other)) { // Front of the list var result = next; next = null; return result; } MulticastDelegate parent = this; while ((parent != null) && (!other.Equals(parent.next))) { parent = parent.next; } if (parent != null) { MulticastDelegate otherx = parent.next; parent.next = otherx.next; otherx.next = null; } return this; }
static public void CallEvent(string objMgPath, string eventName, MulticastDelegate delgt, params object[] eventParams) { try { delgt.DynamicInvoke(eventParams); if (!PurviewMgr.IsMainHost) { object[] newparams = new object[eventParams.Length]; for (int i = 0; i < eventParams.Length; i++) { if (eventParams[i] is IGameObj) { newparams[i] = new GameObjSyncInfo(((IGameObj)eventParams[i]).MgPath); } else { newparams[i] = eventParams[i]; } } // 通过网络协议传递给主机 SyncCasheWriter.SubmitNewEvent(objMgPath, eventName, newparams); } } catch (Exception ex) { Log.Write(ex.ToString()); } }
public void EventUnhooked(MulticastDelegate eventHandler) { // The rest of the method must be inline or the stack trace won't be correct. StackTrace currentStackTrace = new StackTrace(); // Make sure we were called from a "remove" method of an event. string callingEventMethodName = currentStackTrace.GetFrame(1).GetMethod().Name; Debug.Assert(callingEventMethodName.StartsWith("remove_", StringComparison.OrdinalIgnoreCase), "EventUnhooked called from an invalid method"); string eventName = callingEventMethodName.Substring("remove_".Length); if (eventHandler == null) { // If the MulticastDelegate is null, then the event is completely unhooked. _eventsHooked.Remove(eventName); _eventsUnhooked.Remove(eventName); } else { // Save the current stack trace for debugging. if (!_eventsUnhooked.ContainsKey(eventName)) _eventsUnhooked[eventName] = new List<StackTrace>(); _eventsUnhooked[eventName].Add(currentStackTrace); } }
private void InvokeHandler( MulticastDelegate handlerList, EventArgs e ) { object[] args = new object[] { this, e }; foreach( Delegate handler in handlerList.GetInvocationList() ) { object target = handler.Target; System.Windows.Forms.Control control = target as System.Windows.Forms.Control; try { if ( control != null && control.InvokeRequired ) //control.Invoke( handler, args ); control.BeginInvoke(handler, args); else handler.Method.Invoke( target, args ); } catch( Exception ex ) { // TODO: Stop rethrowing this since it goes back to the // Test domain which may not know how to handle it!!! Console.WriteLine( "Exception:" ); Console.WriteLine( ex ); //throw new TestEventInvocationException( ex ); //throw; } } }
public static string BuildFor(MulticastDelegate action, string prefixToExclude) { var name = action.Method.Name; if (name.StartsWith(prefixToExclude, true, CultureInfo.CurrentCulture)) { name = name.Substring(prefixToExclude.Length).TrimStart('_'); } return BuildFor(name); }
/// <summary>Find integral using Lobatto Rule</summary> /// <param name="f">Function to integrate. Must be of the /// form y = f(x) where x and y are of type "double".</param> /// <param name="a">Lower bound of integral</param> /// <param name="b">Upper bound of integral</param> /// <returns>Area under funciton curve with an error of +- 1e-6</returns> /// /// <remarks> /// Derived from "W. Gander and W. Gautschi: Adaptive Quadrature - /// Revisited, BIT Vol. 40, No. 1, March 2000, pp. 84--101. CS technical /// report: Report (gzipped, 82K). Programs: adaptsim.m, adaptlob.m", which /// can be found at: http://www.inf.ethz.ch/personal/gander/. /// /// The defualt error of 1e-6 was chosen in order to give results /// comparible in speed and precision to Matlab R2009a. /// </remarks> public static double quadl(MulticastDelegate f, double a, double b) { double tol = 1e-6; // to have the same level of precision as Matlab // in the future, this could be an input? double m = (a + b) / 2.0; double h = (b - a) / 2.0; double alpha = Math.Sqrt(2.0 / 3.0); double beta = 1.0 / Math.Sqrt(5.0); double c1 = 0.942882415695480; double c2 = 0.641853342345781; double c3 = 0.236383199662150; double y1 = (double)f.DynamicInvoke(a), y2 = (double)f.DynamicInvoke(m - c1 * h), y3 = (double)f.DynamicInvoke(m - alpha * h), y4 = (double)f.DynamicInvoke(m - c2 * h), y5 = (double)f.DynamicInvoke(m - beta * h), y6 = (double)f.DynamicInvoke(m - c3 * h), y7 = (double)f.DynamicInvoke(m), y8 = (double)f.DynamicInvoke(m + c3 * h), y9 = (double)f.DynamicInvoke(m + beta * h), y10= (double)f.DynamicInvoke(m + c2 * h), y11= (double)f.DynamicInvoke(m + alpha * h), y12= (double)f.DynamicInvoke(m + c1 * h), y13= (double)f.DynamicInvoke(b); double fa = y1; double fb = y13; double i2 = (h / 6.0) * (y1 + y13 + 5 * (y5 + y9)); double i1 = (h / 1470.0) * (77 * (y1 + y13) + 432 * (y3 + y11) + 625 * (y5 + y9) + 672 * y7); double i0 = h * ( 0.0158271919734802 * (y1 + y13) + 0.0942738402188500 * (y2 + y12) + 0.155071987336585 * (y3 + y11) + 0.188821573960182 * (y4 + y10) + 0.199773405226859 * (y5 + y9) + 0.224926465333340 * (y6 + y8) + 0.242611071901408 * y7); double s = (i0 >= 0) ? 1 : -1; double erri1 = Math.Abs(i1 - i0); double erri2 = Math.Abs(i2 - i0); double R = (erri2 == 0) ? 1 : erri1 / erri2; i0 = s * Math.Abs(i0) * tol / double.Epsilon; if (i0 == 0) i0 = b - a; return quadlStep(f, a, b, fa, fb, i0); }
/// <summary> /// Raise an event with routines-delegates. /// </summary> /// <param name="evnt">Event to raise</param> /// <param name="action">Routines to start</param> /// <returns>Routine</returns> public static IEnumerator YieldForEach(this System.MulticastDelegate evnt, System.Func <System.Delegate, Coroutine> action) { if (evnt != null) { System.Delegate[] delegates = evnt.GetInvocationList(); foreach (System.Delegate d in delegates) { yield return(action(d)); } } }
public override object Execute(MulticastDelegate dele, ParameterCollection parameters) { try { return dele.DynamicInvoke(parameters.AllParameterValues); } catch (Exception ex) { return this.ExecuteOnException(ex, parameters); } }
public static bool TrySetSlot(MulticastDelegate multicastDelegate, object[] a, int index, object o) { if (a[index] == null) { a[index] = o; } if (a[index] != null) { return false; } return false; }
public static object[] SafeMultiInvoke(MulticastDelegate delegateToFire, params object[] parameters ) { Delegate[] invocationList = delegateToFire.GetInvocationList(); object[] retvals = new object[invocationList.Length]; int i=0; foreach (Delegate dlg in invocationList) { retvals[i++] = SafeInvoke(dlg, parameters); } return retvals; }
public static void UnbindFromEvent(string eventName, object source, MulticastDelegate target) { if (source == null) throw new ArgumentNullException("source"); Type sourceType = source.GetType(); EventInfo targetEvent = sourceType.GetEvent(eventName, BindingFlags.Public | BindingFlags.Instance | BindingFlags.NonPublic); if (targetEvent == null) throw new ArgumentException( string.Format("Event '{0}' was not found on source type '{1}'", eventName, sourceType.FullName)); Type delegateType = targetEvent.EventHandlerType; targetEvent.RemoveEventHandler(source, target); }
public MulticastDelegate Clone() { MulticastDelegate headClone = new MulticastDelegate(Target, Function); MulticastDelegate prevClone = headClone; MulticastDelegate current = headClone._next; MulticastDelegate clone; while (current != null) { clone = new MulticastDelegate(current.Target, current.Function); clone._prev = prevClone; prevClone = clone; current = current._next; } return headClone; }
private bool InvocationListEquals(MulticastDelegate d) { Delegate[] invocationList = m_helperObject as Delegate[]; if (d.m_extraFunctionPointerOrData != m_extraFunctionPointerOrData) return false; int invocationCount = (int)m_extraFunctionPointerOrData; for (int i = 0; i < invocationCount; i++) { Delegate dd = invocationList[i]; Delegate[] dInvocationList = d.m_helperObject as Delegate[]; if (!dd.Equals(dInvocationList[i])) return false; } return true; }
public string TestGetName() { // return this.OnGetName(); System.MulticastDelegate m = (System.MulticastDelegate) this.OnGetName; System.Delegate[] dlist = m.GetInvocationList(); string[] results = new string[dlist.Length]; for (int i = 0; i < dlist.Length; ++i) { object[] p = { /*put your parameters here*/ }; results[i] = System.Convert.ToString(dlist[i].DynamicInvoke(p)); } // return string.Join(",", results); return(Coalesce(results)); }
public override object Execute(MulticastDelegate dele, ParameterCollection parameters) { try { return dele.DynamicInvoke(parameters.AllParameterValues); } catch (Exception ex) { Console.ForegroundColor = ConsoleColor.Black; Console.BackgroundColor = ConsoleColor.Red; Console.WriteLine(ex.Message); Console.ResetColor(); throw; } }
public static void TryInvoke(this System.MulticastDelegate theDelegate, params object[] args) { if (theDelegate == null) { return; } foreach (Delegate handler in theDelegate.GetInvocationList()) { try { handler.DynamicInvoke(args); } catch (Exception ex) { Logger.LogError("Error in MulticastDelegate " + handler.GetType().Name + ": " + ex.ToString()); } } }
public override object Execute(MulticastDelegate dele, ParameterCollection parameters) { Console.ForegroundColor = ConsoleColor.Green; Console.WriteLine("Prefix: {0}", _prefix); Console.WriteLine("Suffix: {0}", _suffix); Console.WriteLine("Name: {0}", this.Name); if (_allTypes != null) { Console.WriteLine("All types: {0}", _allTypes); } Console.WriteLine("Intercepted {0}::{1}", dele.Target.GetType().FullName, dele.Method.Name); if (parameters.Dictionary.Count > 0) { Console.WriteLine("Args:"); foreach (KeyValuePair<string, object> kvp in parameters.Dictionary) { Console.WriteLine(" {0} -> {1}", kvp.Key, kvp.Value); } } Console.ResetColor(); // invoke the intercepted method object result = dele.DynamicInvoke(parameters.AllParameterValues); Console.ForegroundColor = ConsoleColor.Green; if (dele.Method.ReturnType != typeof(void)) { Console.WriteLine("Return:"); Console.WriteLine(" {0}", result); } Console.ResetColor(); return result; }
public string TestGetName_real(System.Type t, string name) { System.MulticastDelegate m = (System.MulticastDelegate) this.OnGetName; System.Delegate[] dlist = m.GetInvocationList(); for (int i = 0; i < dlist.Length; ++i) { // object[] p = { t, name }; object[] p = { /*put your parameters here*/ }; string ret = System.Convert.ToString(dlist[i].DynamicInvoke(p)); if (!string.IsNullOrEmpty(ret) && ret.Trim() != string.Empty) { return(ret); } } // return string.Join(",", results); // return Coalesce(results); throw new System.ArgumentException("Cannot find dependency with this arguments."); }
internal void FireEventToDelegates(MulticastDelegate md, ManagementEventArgs args) { try { if (md != null) { foreach (Delegate delegate2 in md.GetInvocationList()) { try { delegate2.DynamicInvoke(new object[] { this.sender, args }); } catch { } } } } catch { } }
// Recursive function which will check for equality of the invocation list. private bool InvocationListEquals(MulticastDelegate d) { Debug.Assert(d != null && (_invocationList as Object[]) != null, "bogus delegate in multicast list comparison"); Object[] invocationList = _invocationList as Object[]; if (d._invocationCount != _invocationCount) { return(false); } int invocationCount = (int)_invocationCount; for (int i = 0; i < invocationCount; i++) { Delegate dd = (Delegate)invocationList[i]; Object[] dInvocationList = d._invocationList as Object[]; if (!dd.Equals(dInvocationList[i])) { return(false); } } return(true); }
/// <summary> /// Add the given delegate from my invocation list. /// </summary> protected override sealed Delegate Remove(Delegate other) { if (ReferenceEquals(other, this)) { // Front of the list var result = next; next = null; return result; } var parent = this; while ((parent != null) && (!ReferenceEquals(parent.next, other))) { parent = parent.next; } if (parent != null) { var otherx = parent.next; parent.next = otherx.next; otherx.next = null; } return this; }
public static void InvokeMulticast(object sender, MulticastDelegate md, EventArgs e) { if (md == null) return; foreach (StdMulticastDelegation Caster in md.GetInvocationList()) { ISynchronizeInvoke SyncInvoke = Caster.Target as ISynchronizeInvoke; try { if (SyncInvoke != null && SyncInvoke.InvokeRequired) SyncInvoke.Invoke(Caster, new object[] { sender, e }); else Caster(sender, e); } catch (System.Exception ex) { Console.WriteLine("Event handling failed. \n"); Console.WriteLine("{0}:\n", ex.ToString()); } } }
protected override void InternalCombine(Delegate d) { MulticastDelegate current = this; while (current._next != null) // get to the end of the chain { //Console.WriteLine(" -> "); current = current._next; } MulticastDelegate multicastDelegate = d as MulticastDelegate; if (multicastDelegate == null) { //Console.WriteLine("Creating new secondary multicast delegate for InternalCombine"); multicastDelegate = new MulticastDelegate(d.Target, d.Function); } else { //Console.WriteLine("Cloning secondary delegate for InternalCombine"); multicastDelegate = multicastDelegate.Clone(); } current._next = multicastDelegate; multicastDelegate._prev = current; }
// This method will combine this delegate with the passed delegate // to form a new delegate. //| <include path='docs/doc[@for="MulticastDelegate.CombineImpl"]/*' /> protected override sealed Delegate CombineImpl(Delegate follow) { // Verify that the types are the same... if (this.GetType() != follow.GetType()) { throw new ArgumentException("Arg_DlgtTypeMis"); } // We always clone the delegate because this delegate is // not changed by combine and remove. We can safely tack // the follow delegate onto the end of the copy. MulticastDelegate d = (MulticastDelegate)((MulticastDelegate)follow).MemberwiseClone(); MulticastDelegate root = d; while (d._prev != null) { d._prev = (MulticastDelegate)d._prev.MemberwiseClone(); d = d._prev; } d._prev = (MulticastDelegate)this; return(root); }
private bool TrySetSlot(Object[] a, int index, Object o) { if (a[index] == null && System.Threading.Interlocked.CompareExchange <Object>(ref a[index], o, null) == null) { return(true); } // The slot may be already set because we have added and removed the same method before. // Optimize this case, because it's cheaper than copying the array. if (a[index] != null) { MulticastDelegate d = (MulticastDelegate)o; MulticastDelegate dd = (MulticastDelegate)a[index]; if (dd._methodPtr == d._methodPtr && dd._target == d._target && dd._methodPtrAux == d._methodPtrAux) { return(true); } } return(false); }
private bool TrySetSlot(object?[] a, int index, object o) { if (a[index] == null && System.Threading.Interlocked.CompareExchange <object?>(ref a[index], o, null) == null) { return(true); } // The slot may be already set because we have added and removed the same method before. // Optimize this case, because it's cheaper than copying the array. if (a[index] != null) { MulticastDelegate d = (MulticastDelegate)o; MulticastDelegate dd = (MulticastDelegate)a[index] !; // TODO-NULLABLE: https://github.com/dotnet/roslyn/issues/34644 if (dd._methodPtr == d._methodPtr && dd._target == d._target && dd._methodPtrAux == d._methodPtrAux) { return(true); } } return(false); }
private MulticastDelegate NewMulticastDelegate(Object[] invocationList, int invocationCount, bool thisIsMultiCastAlready) { // First, allocate a new multicast delegate just like this one, i.e. same type as the this object MulticastDelegate result = (MulticastDelegate)InternalAllocLike(this); // Performance optimization - if this already points to a true multicast delegate, // copy _methodPtr and _methodPtrAux fields rather than calling into the EE to get them if (thisIsMultiCastAlready) { result._methodPtr = this._methodPtr; result._methodPtrAux = this._methodPtrAux; } else { result._methodPtr = GetMulticastInvoke(); result._methodPtrAux = GetInvokeMethod(); } result._target = result; result._invocationList = invocationList; result._invocationCount = (IntPtr)invocationCount; return(result); }
private MulticastDelegate[] DeleteFromInvocationList(MulticastDelegate[] invocationList, int invocationCount, int deleteIndex, int deleteCount) { MulticastDelegate[] thisInvocationList = _invocationList; int allocCount = thisInvocationList.Length; while (allocCount / 2 >= invocationCount - deleteCount) { allocCount /= 2; } MulticastDelegate[] newInvocationList = new MulticastDelegate[allocCount]; for (int i = 0; i < deleteIndex; i++) { newInvocationList[i] = invocationList[i]; } for (int i = deleteIndex + deleteCount; i < invocationCount; i++) { newInvocationList[i - deleteCount] = invocationList[i]; } return(newInvocationList); }
public override void GetObjectData(SerializationInfo info, StreamingContext context) { Delegate[] invocationList = m_helperObject as Delegate[]; if (invocationList == null) { if (Method == null) { throw new SerializationException(SR.DelegateSer_InsufficientMetadata); } DelegateSerializationHolder.GetDelegateSerializationInfo(info, this.GetType(), Target, Method, 0); } else { int targetIndex = 0; DelegateSerializationHolder.DelegateEntry previousEntry = null; int invocationCount = (int)m_extraFunctionPointerOrData; for (int i = invocationCount; --i >= 0;) { MulticastDelegate d = (MulticastDelegate)invocationList[i]; if (d.Method == null) { throw new SerializationException(SR.DelegateSer_InsufficientMetadata); } DelegateSerializationHolder.DelegateEntry de = DelegateSerializationHolder.GetDelegateSerializationInfo(info, d.GetType(), d.Target, d.Method, targetIndex++); if (previousEntry != null) { previousEntry.NextEntry = de; } previousEntry = de; } } }
private bool TrySetSlot(Delegate[] a, int index, Delegate o) { if (a[index] == null && System.Threading.Interlocked.CompareExchange <Delegate>(ref a[index], o, null) == null) { return(true); } // The slot may be already set because we have added and removed the same method before. // Optimize this case, because it's cheaper than copying the array. if (a[index] != null) { MulticastDelegate d = (MulticastDelegate)o; MulticastDelegate dd = (MulticastDelegate)a[index]; if (object.ReferenceEquals(dd.m_firstParameter, d.m_firstParameter) && object.ReferenceEquals(dd.m_helperObject, d.m_helperObject) && dd.m_extraFunctionPointerOrData == d.m_extraFunctionPointerOrData && dd.m_functionPointer == d.m_functionPointer) { return(true); } } return(false); }
/// <summary>Initializes a new instance of the <see cref="T:System.MulticastDelegate" /> class.</summary> /// <param name="target">The type of object on which <paramref name="method" /> is defined. </param> /// <param name="method">The name of the static method for which a delegate is created. </param> /// <exception cref="T:System.MemberAccessException">Cannot create an instance of an abstract class, or this member was invoked with a late-binding mechanism. </exception> protected MulticastDelegate(Type target, string method) : base(target, method) { this.prev = null; }
private static MulticastDelegate KPM(MulticastDelegate needle, MulticastDelegate haystack, out MulticastDelegate tail) { MulticastDelegate multicastDelegate = needle; MulticastDelegate multicastDelegate2 = needle.kpm_next = null; for (;;) { while (multicastDelegate2 != null && !multicastDelegate2.BaseEquals(multicastDelegate)) { multicastDelegate2 = multicastDelegate2.kpm_next; } multicastDelegate = multicastDelegate.prev; if (multicastDelegate == null) { break; } multicastDelegate2 = ((multicastDelegate2 != null) ? multicastDelegate2.prev : needle); if (multicastDelegate.BaseEquals(multicastDelegate2)) { multicastDelegate.kpm_next = multicastDelegate2.kpm_next; } else { multicastDelegate.kpm_next = multicastDelegate2; } } MulticastDelegate multicastDelegate3 = haystack; multicastDelegate2 = needle; multicastDelegate = haystack; for (;;) { while (multicastDelegate2 != null && !multicastDelegate2.BaseEquals(multicastDelegate)) { multicastDelegate2 = multicastDelegate2.kpm_next; multicastDelegate3 = multicastDelegate3.prev; } multicastDelegate2 = ((multicastDelegate2 != null) ? multicastDelegate2.prev : needle); if (multicastDelegate2 == null) { break; } multicastDelegate = multicastDelegate.prev; if (multicastDelegate == null) { goto Block_8; } } tail = multicastDelegate.prev; return(multicastDelegate3); Block_8: tail = null; return(null); }
private bool BaseEquals(MulticastDelegate value) { return(base.Equals(value)); }
/// <summary> /// Raise an event with routines-delegates. /// </summary> /// <param name="evnt">Event to raise</param> /// <param name="runner">Routine runner</param> /// <param name="action">Routines to start</param> /// <returns>Coroutine</returns> public static Coroutine YieldForEach(this System.MulticastDelegate evnt, MonoBehaviour runner, System.Func <System.Delegate, IEnumerator> action) { return(runner.StartCoroutine(evnt.YieldForEach((d) => runner.StartCoroutine(action(d))))); }
private bool BaseEquals (MulticastDelegate value) { return base.Equals (value); }
private static extern void Enumerate(IntPtr ptr, MulticastDelegate predicate);
protected override Delegate CombineImpl(Delegate follow) { if (follow == null) { return(this); } // Verify that the types are the same... if (this.GetType() != follow.GetType()) { throw new ArgumentException("DlgtTypeMis"); } MulticastDelegate dFollow = (MulticastDelegate)follow; MulticastDelegate[] resultList; int followCount = 1; MulticastDelegate[] followList = dFollow._invocationList; if (followList != null) { followCount = (int)dFollow._invocationCount; } int resultCount; MulticastDelegate[] invocationList = _invocationList; if (invocationList == null) { resultCount = 1 + followCount; resultList = new MulticastDelegate[resultCount]; resultList[0] = this; if (followList == null) { resultList[1] = dFollow; } else { for (int i = 0; i < followCount; i++) { resultList[1 + i] = followList[i]; } } return(NewMulticastDelegate(resultList, resultCount)); } else { int invocationCount = (int)_invocationCount; resultCount = invocationCount + followCount; resultList = null; if (resultCount <= invocationList.Length) { resultList = invocationList; if (followList == null) { if (!TrySetSlot(resultList, invocationCount, dFollow)) { resultList = null; } } else { for (int i = 0; i < followCount; i++) { if (!TrySetSlot(resultList, invocationCount + i, followList[i])) { resultList = null; break; } } } } if (resultList == null) { int allocCount = invocationList.Length; while (allocCount < resultCount) { allocCount *= 2; } resultList = new MulticastDelegate[allocCount]; for (int i = 0; i < invocationCount; i++) { resultList[i] = invocationList[i]; } if (followList == null) { resultList[invocationCount] = dFollow; } else { for (int i = 0; i < followCount; i++) { resultList[invocationCount + i] = followList[i]; } } } return(NewMulticastDelegate(resultList, resultCount)); } }
public static void ConfigureStaticEventHandler(object obj, string objEventName, string handlerMethodName, bool attach) { // use reflection to assign delegate method to event // get type for the handler class (this class) from the handler assembly Type handlerClassType = System.Reflection.MethodBase.GetCurrentMethod().DeclaringType; if (handlerClassType == null) { throw new Exception(String.Format("Cannot get handler class type")); } #if BP_DO_EXISTING_DELEGATE_TEST // determine if required delegate exists bool delegateExists = false; // get the delegate fields for the given event // note that this will only work for field-like events. // notably this approach works for the Dubrovnik unit tests but fails with EntityFramework objects! FieldInfo eventFieldInfo = obj.GetType().GetField(objEventName, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance); if (eventFieldInfo != null) { System.MulticastDelegate eventHandler = eventFieldInfo.GetValue(obj) as System.MulticastDelegate; if (eventHandler != null) { foreach (Delegate dg in eventHandler.GetInvocationList()) { MethodInfo delegateMethodInfo = dg.Method; // does the existing delegate method target the incoming method if (delegateMethodInfo.Name == handlerMethodName && delegateMethodInfo.DeclaringType == handlerClassType && dg.Target == null) { delegateExists = true; break; } } } } else // we only want to register events once against this object. // we similarly only want to delete existing delegates if (attach && delegateExists || !attach && !delegateExists) { return; } #endif // get info for the event from the type. // note that if we are attaching to a static event handler then the obj parameter will be a System.Type instance. Type t; if (obj is System.Type) { t = (Type)obj; } else { t = obj.GetType(); } EventInfo evInfo = t.GetEvent(objEventName); if (evInfo == null) { throw new Exception(String.Format("Cannot locate event: {0} on object of type : {1}", objEventName, obj.GetType().ToString())); } // get method info for the managed handler method MethodInfo handlerMethod = handlerClassType.GetMethod(handlerMethodName, BindingFlags.Public | BindingFlags.FlattenHierarchy | BindingFlags.Static); if (handlerMethod == null) { throw new Exception(String.Format("Cannot get method info for handler : {0}", handlerMethodName)); } // create delegate Type delegateType = evInfo.EventHandlerType; Delegate theDelegate = Delegate.CreateDelegate(delegateType, null, handlerMethod); if (theDelegate == null) { throw new Exception(String.Format("Cannot create delegate for handler : {0}", handlerMethodName)); } // invoke the add | remove method on the event MethodInfo evMethod = attach ? evInfo.GetAddMethod() : evInfo.GetRemoveMethod(); Object[] args = { theDelegate }; evMethod.Invoke(obj, args); }
[System.Security.SecuritySafeCritical] // auto-generated public override sealed bool Equals(Object obj) { if (obj == null || !InternalEqualTypes(this, obj)) { return(false); } MulticastDelegate d = obj as MulticastDelegate; if (d == null) { return(false); } if (_invocationCount != (IntPtr)0) { // there are 4 kind of delegate kinds that fall into this bucket // 1- Multicast (_invocationList is Object[]) // 2- Secure/Wrapper (_invocationList is Delegate) // 3- Unmanaged FntPtr (_invocationList == null) // 4- Open virtual (_invocationCount == MethodDesc of target, _invocationList == null, LoaderAllocator, or DynamicResolver) if (InvocationListLogicallyNull()) { if (IsUnmanagedFunctionPtr()) { if (!d.IsUnmanagedFunctionPtr()) { return(false); } return(CompareUnmanagedFunctionPtrs(this, d)); } // now we know 'this' is not a special one, so we can work out what the other is if ((d._invocationList as Delegate) != null) { // this is a secure/wrapper delegate so we need to unwrap and check the inner one return(Equals(d._invocationList)); } return(base.Equals(obj)); } else { if ((_invocationList as Delegate) != null) { // this is a secure/wrapper delegate so we need to unwrap and check the inner one return(_invocationList.Equals(obj)); } else { Contract.Assert((_invocationList as Object[]) != null, "empty invocation list on multicast delegate"); return(InvocationListEquals(d)); } } } else { // among the several kind of delegates falling into this bucket one has got a non // empty _invocationList (open static with special sig) // to be equals we need to check that _invocationList matches (both null is fine) // and call the base.Equals() if (!InvocationListLogicallyNull()) { if (!_invocationList.Equals(d._invocationList)) { return(false); } return(base.Equals(d)); } // now we know 'this' is not a special one, so we can work out what the other is if ((d._invocationList as Delegate) != null) { // this is a secure/wrapper delegate so we need to unwrap and check the inner one return(Equals(d._invocationList)); } // now we can call on the base return(base.Equals(d)); } }
// equals returns true IIF the delegate is not null and has the // same target, method and invocation list as this object public sealed override bool Equals([NotNullWhen(true)] object?obj) { if (obj == null) { return(false); } if (object.ReferenceEquals(this, obj)) { return(true); } if (!InternalEqualTypes(this, obj)) { return(false); } // Since this is a MulticastDelegate and we know // the types are the same, obj should also be a // MulticastDelegate Debug.Assert( obj is MulticastDelegate, "Shouldn't have failed here since we already checked the types are the same!" ); MulticastDelegate d = Unsafe.As <MulticastDelegate>(obj); if (_invocationCount != (IntPtr)0) { // there are 4 kind of delegate kinds that fall into this bucket // 1- Multicast (_invocationList is Object[]) // 2- Wrapper (_invocationList is Delegate) // 3- Unmanaged FntPtr (_invocationList == null) // 4- Open virtual (_invocationCount == MethodDesc of target, _invocationList == null, LoaderAllocator, or DynamicResolver) if (InvocationListLogicallyNull()) { if (IsUnmanagedFunctionPtr()) { if (!d.IsUnmanagedFunctionPtr()) { return(false); } return(CompareUnmanagedFunctionPtrs(this, d)); } // now we know 'this' is not a special one, so we can work out what the other is if (d._invocationList is Delegate) { // this is a wrapper delegate so we need to unwrap and check the inner one return(Equals(d._invocationList)); } return(base.Equals(obj)); } else { if (_invocationList is Delegate invocationListDelegate) { // this is a wrapper delegate so we need to unwrap and check the inner one return(invocationListDelegate.Equals(obj)); } else { Debug.Assert( _invocationList is object[], "empty invocation list on multicast delegate" ); return(InvocationListEquals(d)); } } } else { // among the several kind of delegates falling into this bucket one has got a non // empty _invocationList (open static with special sig) // to be equals we need to check that _invocationList matches (both null is fine) // and call the base.Equals() if (!InvocationListLogicallyNull()) { if (!_invocationList !.Equals(d._invocationList)) { return(false); } return(base.Equals(d)); } // now we know 'this' is not a special one, so we can work out what the other is if (d._invocationList is Delegate) { // this is a wrapper delegate so we need to unwrap and check the inner one return(Equals(d._invocationList)); } // now we can call on the base return(base.Equals(d)); } }
public static void ConfigureStaticEventHandler(object obj, string objEventName, string handlerMethodName, bool attach) { // use reflection to assign delegate method to event // get type for the handler class (this class) from the handler assembly Type handlerClassType = System.Reflection.MethodBase.GetCurrentMethod().DeclaringType; if (handlerClassType == null) { throw new Exception(String.Format("Cannot get handler class type")); } // determine if required delegate exists bool delegateExists = false; // get the delegate fields for the given event. // NOTE: this is unreliable and ONLY works for field-like events FieldInfo eventFieldInfo = obj.GetType().GetField(objEventName, BindingFlags.NonPublic | BindingFlags.Instance); if (eventFieldInfo != null) { System.MulticastDelegate eventHandler = eventFieldInfo.GetValue(obj) as System.MulticastDelegate; if (eventHandler != null) { foreach (Delegate dg in eventHandler.GetInvocationList()) { MethodInfo delegateMethodInfo = dg.Method; Console.WriteLine("Method name = {0} ", delegateMethodInfo.Name); Console.WriteLine("Method declaring type = {0} ", delegateMethodInfo.DeclaringType); Console.WriteLine("Delegate target = {0} ", dg.Target); // does the existing delegate method target the incoming method if (delegateMethodInfo.Name == handlerMethodName && delegateMethodInfo.DeclaringType == handlerClassType && dg.Target == null) { delegateExists = true; break; } } } } // we only want to register events once against this object. // we similarly only want to delete existing delegates if (attach && delegateExists || !attach && !delegateExists) { Console.WriteLine("DELEGATE EXISTS"); return; } Console.WriteLine("DELEGATE WILL BE ADDED"); // get info for the event EventInfo evInfo = obj.GetType().GetEvent(objEventName); if (evInfo == null) { throw new Exception(String.Format("Cannot locate event: {0} on object of type : {1}", objEventName, obj.GetType().ToString())); } // get method info for the managed handler method MethodInfo handlerMethod = handlerClassType.GetMethod(handlerMethodName, BindingFlags.Public | BindingFlags.FlattenHierarchy | BindingFlags.Static); if (handlerMethod == null) { throw new Exception(String.Format("Cannot get method info for handler : {0}", handlerMethodName)); } // create delegate Type delegateType = evInfo.EventHandlerType; Delegate theDelegate = Delegate.CreateDelegate(delegateType, null, handlerMethod); if (theDelegate == null) { throw new Exception(String.Format("Cannot create delegate for handler : {0}", handlerMethodName)); } // invoke the add | remove method on the event MethodInfo evMethod = attach ? evInfo.GetAddMethod() : evInfo.GetRemoveMethod(); Object[] args = { theDelegate }; evMethod.Invoke(obj, args); }
private static extern int OSP_Unity_AssignRayCastCallback(System.MulticastDelegate callback, System.IntPtr data);
protected MulticastDelegate(object target, string method) : base(target, method) { prev = null; }
// This method will combine this delegate with the passed delegate // to form a new delegate. protected virtual Delegate CombineImpl(Delegate d) { if ((object)d == null) // cast to object for a more efficient test { return(this); } // Verify that the types are the same... if (!InternalEqualTypes(this, d)) { throw new ArgumentException(); } if (IsDynamicDelegate() && d.IsDynamicDelegate()) { throw new InvalidOperationException(); } MulticastDelegate dFollow = (MulticastDelegate)d; Delegate[] resultList; int followCount = 1; Delegate[] followList = dFollow.m_helperObject as Delegate[]; if (followList != null) { followCount = (int)dFollow.m_extraFunctionPointerOrData; } int resultCount; Delegate[] invocationList = m_helperObject as Delegate[]; if (invocationList == null) { resultCount = 1 + followCount; resultList = new Delegate[resultCount]; resultList[0] = this; if (followList == null) { resultList[1] = dFollow; } else { for (int i = 0; i < followCount; i++) { resultList[1 + i] = followList[i]; } } return(NewMulticastDelegate(resultList, resultCount)); } else { int invocationCount = (int)m_extraFunctionPointerOrData; resultCount = invocationCount + followCount; resultList = null; if (resultCount <= invocationList.Length) { resultList = invocationList; if (followList == null) { if (!TrySetSlot(resultList, invocationCount, dFollow)) { resultList = null; } } else { for (int i = 0; i < followCount; i++) { if (!TrySetSlot(resultList, invocationCount + i, followList[i])) { resultList = null; break; } } } } if (resultList == null) { int allocCount = invocationList.Length; while (allocCount < resultCount) { allocCount *= 2; } resultList = new Delegate[allocCount]; for (int i = 0; i < invocationCount; i++) { resultList[i] = invocationList[i]; } if (followList == null) { resultList[invocationCount] = dFollow; } else { for (int i = 0; i < followCount; i++) { resultList[invocationCount + i] = followList[i]; } } } return(NewMulticastDelegate(resultList, resultCount, true)); } }
// This method currently looks backward on the invocation list // for an element that has Delegate based equality with value. (Doesn't // look at the invocation list.) If this is found we remove it from // this list and return a new delegate. If its not found a copy of the // current list is returned. protected override sealed Delegate RemoveImpl(Delegate value) { // There is a special case were we are removing using a delegate as // the value we need to check for this case // MulticastDelegate v = value as MulticastDelegate; if (v == null) { return(this); } if (v._invocationList as Object[] == null) { Object[] invocationList = _invocationList as Object[]; if (invocationList == null) { // they are both not real Multicast if (this.Equals(value)) { return(null); } } else { int invocationCount = (int)_invocationCount; for (int i = invocationCount; --i >= 0;) { if (value.Equals(invocationList[i])) { if (invocationCount == 2) { // Special case - only one value left, either at the beginning or the end return((Delegate)invocationList[1 - i]); } else { Object[] list = DeleteFromInvocationList(invocationList, invocationCount, i, 1); return(NewMulticastDelegate(list, invocationCount - 1, true)); } } } } } else { Object[] invocationList = _invocationList as Object[]; if (invocationList != null) { int invocationCount = (int)_invocationCount; int vInvocationCount = (int)v._invocationCount; for (int i = invocationCount - vInvocationCount; i >= 0; i--) { if (EqualInvocationLists(invocationList, v._invocationList as Object[], i, vInvocationCount)) { if (invocationCount - vInvocationCount == 0) { // Special case - no values left return(null); } else if (invocationCount - vInvocationCount == 1) { // Special case - only one value left, either at the beginning or the end return((Delegate)invocationList[i != 0 ? 0 : invocationCount - 1]); } else { Object[] list = DeleteFromInvocationList(invocationList, invocationCount, i, vInvocationCount); return(NewMulticastDelegate(list, invocationCount - vInvocationCount, true)); } } } } } return(this); }
// This method will combine this delegate with the passed delegate // to form a new delegate. protected override sealed Delegate CombineImpl(Delegate follow) { if ((Object)follow == null) // cast to object for a more efficient test { return(this); } // Verify that the types are the same... if (!InternalEqualTypes(this, follow)) { throw new ArgumentException(SR.Arg_DlgtTypeMis); } MulticastDelegate dFollow = (MulticastDelegate)follow; Object[] resultList; int followCount = 1; Object[] followList = dFollow._invocationList as Object[]; if (followList != null) { followCount = (int)dFollow._invocationCount; } int resultCount; Object[] invocationList = _invocationList as Object[]; if (invocationList == null) { resultCount = 1 + followCount; resultList = new Object[resultCount]; resultList[0] = this; if (followList == null) { resultList[1] = dFollow; } else { for (int i = 0; i < followCount; i++) { resultList[1 + i] = followList[i]; } } return(NewMulticastDelegate(resultList, resultCount)); } else { int invocationCount = (int)_invocationCount; resultCount = invocationCount + followCount; resultList = null; if (resultCount <= invocationList.Length) { resultList = invocationList; if (followList == null) { if (!TrySetSlot(resultList, invocationCount, dFollow)) { resultList = null; } } else { for (int i = 0; i < followCount; i++) { if (!TrySetSlot(resultList, invocationCount + i, followList[i])) { resultList = null; break; } } } } if (resultList == null) { int allocCount = invocationList.Length; while (allocCount < resultCount) { allocCount *= 2; } resultList = new Object[allocCount]; for (int i = 0; i < invocationCount; i++) { resultList[i] = invocationList[i]; } if (followList == null) { resultList[invocationCount] = dFollow; } else { for (int i = 0; i < followCount; i++) { resultList[invocationCount + i] = followList[i]; } } } return(NewMulticastDelegate(resultList, resultCount, true)); } }
// This method currently looks backward on the invocation list // for an element that has Delegate based equality with value. (Doesn't // look at the invocation list.) If this is found we remove it from // this list and return a new delegate. If its not found a copy of the // current list is returned. protected virtual Delegate RemoveImpl(Delegate d) { // There is a special case were we are removing using a delegate as // the value we need to check for this case // MulticastDelegate v = d as MulticastDelegate; if (v == null) { return(this); } if (v.m_helperObject as Delegate[] == null) { Delegate[] invocationList = m_helperObject as Delegate[]; if (invocationList == null) { // they are both not real Multicast if (this.Equals(d)) { return(null); } } else { int invocationCount = (int)m_extraFunctionPointerOrData; for (int i = invocationCount; --i >= 0;) { if (d.Equals(invocationList[i])) { if (invocationCount == 2) { // Special case - only one value left, either at the beginning or the end return(invocationList[1 - i]); } else { Delegate[] list = DeleteFromInvocationList(invocationList, invocationCount, i, 1); return(NewMulticastDelegate(list, invocationCount - 1, true)); } } } } } else { Delegate[] invocationList = m_helperObject as Delegate[]; if (invocationList != null) { int invocationCount = (int)m_extraFunctionPointerOrData; int vInvocationCount = (int)v.m_extraFunctionPointerOrData; for (int i = invocationCount - vInvocationCount; i >= 0; i--) { if (EqualInvocationLists(invocationList, v.m_helperObject as Delegate[], i, vInvocationCount)) { if (invocationCount - vInvocationCount == 0) { // Special case - no values left return(null); } else if (invocationCount - vInvocationCount == 1) { // Special case - only one value left, either at the beginning or the end return(invocationList[i != 0 ? 0 : invocationCount - 1]); } else { Delegate[] list = DeleteFromInvocationList(invocationList, invocationCount, i, vInvocationCount); return(NewMulticastDelegate(list, invocationCount - vInvocationCount, true)); } } } } } return(this); }
private static extern void CountConst(IntPtr ptr, MulticastDelegate predicate);
private static extern MulticastDelegate CreateDelegateLike(MulticastDelegate @delegate, Delegate[] invocationList);
private static extern void Graph(IntPtr ptr, MulticastDelegate predicate);
protected sealed override Delegate RemoveImpl (Delegate value) { if (value == null) return this; // match this with value MulticastDelegate head, tail; head = KPM ((MulticastDelegate)value, this, out tail); if (head == null) return this; // duplicate chain without head..tail MulticastDelegate prev = null, retval = null, orig; for (orig = this; (object)orig != (object)head; orig = orig.prev) { MulticastDelegate clone = (MulticastDelegate)orig.Clone (); if (prev != null) prev.prev = clone; else retval = clone; prev = clone; } for (orig = tail; (object)orig != null; orig = orig.prev) { MulticastDelegate clone = (MulticastDelegate)orig.Clone (); if (prev != null) prev.prev = clone; else retval = clone; prev = clone; } if (prev != null) prev.prev = null; return retval; }
/* * Perform a slightly crippled version of * Knuth-Pratt-Morris over MulticastDelegate chains. * Border values are set as pointers in kpm_next; * Generally, KPM border arrays are length n+1 for * strings of n. This one works with length n at the * expense of a few additional comparisions. */ private static MulticastDelegate KPM (MulticastDelegate needle, MulticastDelegate haystack, out MulticastDelegate tail) { MulticastDelegate nx, hx; // preprocess hx = needle; nx = needle.kpm_next = null; do { while ((nx != null) && (!nx.BaseEquals (hx))) nx = nx.kpm_next; hx = hx.prev; if (hx == null) break; nx = nx == null ? needle : nx.prev; if (hx.BaseEquals (nx)) hx.kpm_next = nx.kpm_next; else hx.kpm_next = nx; } while (true); // match MulticastDelegate match = haystack; nx = needle; hx = haystack; do { while (nx != null && !nx.BaseEquals (hx)) { nx = nx.kpm_next; match = match.prev; } nx = nx == null ? needle : nx.prev; if (nx == null) { // bingo tail = hx.prev; return match; } hx = hx.prev; } while (hx != null); tail = null; return null; }
protected sealed override Delegate RemoveImpl(Delegate value) { if (value == null) { return(this); } MulticastDelegate other = (MulticastDelegate)value; if (delegates == null && other.delegates == null) { /* if they are not equal and the current one is not * a multicastdelegate then we cannot delete it */ return(this.Equals(other) ? null : this); } else if (delegates == null) { foreach (Delegate?d in other.delegates) { if (this.Equals(d)) { return(null); } } return(this); } else if (other.delegates == null) { int idx = Array.LastIndexOf(delegates, other); if (idx == -1) { return(this); } if (delegates.Length <= 1) { /* delegates.Length should never be equal or * lower than 1, it should be 2 or greater */ throw new InvalidOperationException(); } if (delegates.Length == 2) { return(delegates[idx == 0 ? 1 : 0]); } MulticastDelegate ret = AllocDelegateLike_internal(this); ret.delegates = new Delegate[delegates.Length - 1]; Array.Copy(delegates, ret.delegates, idx); Array.Copy(delegates, idx + 1, ret.delegates, idx, delegates.Length - idx - 1); return(ret); } else { /* wild case : remove MulticastDelegate from MulticastDelegate * complexity is O(m + n), with n the number of elements in * this.delegates and m the number of elements in other.delegates */ if (delegates.Equals(other.delegates)) { return(null); } /* we need to remove elements from the end to the beginning, as * the addition and removal of delegates behaves like a stack */ int idx = LastIndexOf(delegates, other.delegates); if (idx == -1) { return(this); } MulticastDelegate ret = AllocDelegateLike_internal(this); ret.delegates = new Delegate[delegates.Length - other.delegates.Length]; Array.Copy(delegates, ret.delegates, idx); Array.Copy(delegates, idx + other.delegates.Length, ret.delegates, idx, delegates.Length - idx - other.delegates.Length); return(ret); } }
protected MulticastDelegate (Type target, string method) : base (target, method) { prev = null; }
protected override sealed Delegate RemoveImpl(Delegate value) { MulticastDelegate v = value as MulticastDelegate; if (v == null) { return(this); } if (v._invocationList == null) { MulticastDelegate[] invocationList = _invocationList; if (invocationList == null) { if (this.Equals(value)) { return(null); } } else { int invocationCount = (int)_invocationCount; for (int i = invocationCount; --i >= 0;) { if (value.Equals(invocationList[i])) { if (invocationCount == 2) { // Special case - only one value left, either at the beginning or the end return((Delegate)invocationList[1 - i]); } else { MulticastDelegate[] list = DeleteFromInvocationList(invocationList, invocationCount, i, 1); return(NewMulticastDelegate(list, invocationCount - 1)); } } } } } else { MulticastDelegate[] invocationList = _invocationList; if (invocationList != null) { int invocationCount = (int)_invocationCount; int vInvocationCount = (int)v._invocationCount; for (int i = invocationCount - vInvocationCount; i >= 0; i--) { if (EqualInvocationLists(invocationList, v._invocationList, i, vInvocationCount)) { if (invocationCount - vInvocationCount == 0) { return(null); } else if (invocationCount - vInvocationCount == 1) { return((Delegate)invocationList[i != 0 ? 0 : invocationCount - 1]); } else { MulticastDelegate[] list = DeleteFromInvocationList(invocationList, invocationCount, i, vInvocationCount); return(NewMulticastDelegate(list, invocationCount - vInvocationCount)); } } } } } return(this); }