public void TestInternalNestedClassPrivateNamedMethod() { Reset(); const int index = 99; _itemInternal = new InternalNestedTestClass(index); _reference = new WeakReference(_itemInternal); _action = _itemInternal.GetAction(WeakActionTestCase.PrivateNamedMethod); Assert.IsTrue(_reference.IsAlive); Assert.IsTrue(_action.IsAlive); _action.Execute(); Assert.AreEqual( InternalNestedTestClass.Expected + InternalNestedTestClass.Private + index, InternalNestedTestClass.Result); _itemInternal = null; GC.Collect(); #if SILVERLIGHT Assert.IsTrue(_reference.IsAlive); // Anonymous, private and internal methods cannot be GCed _action = null; GC.Collect(); Assert.IsFalse(_reference.IsAlive); #else Assert.IsFalse(_reference.IsAlive); #endif }
public void TestPublicClassPublicNamedMethod() { Reset(); const int index = 99; _itemPublic = new PublicTestClass(index); _action = _itemPublic.GetAction(WeakActionTestCase.PublicNamedMethod); _reference = new WeakReference(_itemPublic); Assert.IsTrue(_reference.IsAlive); Assert.IsTrue(_action.IsAlive); _action.Execute(); Assert.AreEqual( PublicTestClass.Expected + PublicTestClass.Public + index, PublicTestClass.Result); _itemPublic = null; GC.Collect(); Assert.IsFalse(_reference.IsAlive); }
public void TestPublicClassInternalNamedMethod() { Reset(); const string parameter = "My parameter"; const int index = 99; _itemPublic = new PublicNestedTestClass <string>(index); _reference = new WeakReference(_itemPublic); _action = _itemPublic.GetAction(WeakActionTestCase.InternalNamedMethod); Assert.IsTrue(_reference.IsAlive); Assert.IsTrue(_action.IsAlive); _action.Execute(parameter); Assert.AreEqual( PublicNestedTestClass <string> .Expected + PublicNestedTestClass <string> .Internal + index + parameter, PublicNestedTestClass <string> .Result); _itemPublic = null; GC.Collect(); #if SILVERLIGHT Assert.IsTrue(_reference.IsAlive); // Anonymous, private and internal methods cannot be GCed _action = null; GC.Collect(); Assert.IsFalse(_reference.IsAlive); #else Assert.IsFalse(_reference.IsAlive); #endif }
public void TestPublicClassAnonymousMethod() { Reset(); const int index = 99; _itemPublic = new PublicTestClass(index); _reference = new WeakReference(_itemPublic); _action = _itemPublic.GetAction(WeakActionTestCase.AnonymousMethod); Assert.IsTrue(_reference.IsAlive); Assert.IsTrue(_action.IsAlive); _action.Execute(); Assert.AreEqual( PublicTestClass.Expected + index, PublicTestClass.Result); _itemPublic = null; GC.Collect(); #if SILVERLIGHT Assert.IsTrue(_reference.IsAlive); // Anonymous, private and internal methods cannot be GCed _action = null; GC.Collect(); Assert.IsFalse(_reference.IsAlive); #else Assert.IsFalse(_reference.IsAlive); #endif }
public void TestPublicClassPublicStaticMethod() { Reset(); const string parameter = "My parameter"; _itemPublic = new PublicNestedTestClass <string>(); _reference = new WeakReference(_itemPublic); _action = _itemPublic.GetAction(WeakActionTestCase.PublicStaticMethod); Assert.IsTrue(_reference.IsAlive); Assert.IsTrue(_action.IsAlive); _action.Execute(parameter); Assert.AreEqual( PublicNestedTestClass <string> .Expected + PublicNestedTestClass <string> .PublicStatic + parameter, PublicNestedTestClass <string> .Result); _itemPublic = null; GC.Collect(); Assert.IsFalse(_reference.IsAlive); }
public void TestPrivateClassAnonymousStaticMethod() { Reset(); const string parameter = "My parameter"; _itemPrivate = new PrivateNestedTestClass <string>(); _reference = new WeakReference(_itemPrivate); _action = _itemPrivate.GetAction(WeakActionTestCase.AnonymousStaticMethod); Assert.IsTrue(_reference.IsAlive); Assert.IsTrue(_action.IsAlive); _action.Execute(parameter); Assert.AreEqual( PrivateNestedTestClass <string> .Expected + parameter, PrivateNestedTestClass <string> .Result); _itemPrivate = null; GC.Collect(); Assert.IsFalse(_reference.IsAlive); }
public void TestInternalClassPrivateStaticMethod() { Reset(); const string parameter = "My parameter"; _itemInternal = new InternalNestedTestClass <string>(); _reference = new WeakReference(_itemInternal); _action = _itemInternal.GetAction(WeakActionTestCase.PrivateStaticMethod); Assert.IsTrue(_reference.IsAlive); Assert.IsTrue(_action.IsAlive); _action.Execute(parameter); Assert.AreEqual( InternalNestedTestClass <string> .Expected + InternalNestedTestClass <string> .PrivateStatic + parameter, InternalNestedTestClass <string> .Result); _itemInternal = null; GC.Collect(); Assert.IsFalse(_reference.IsAlive); }
/// <summary> /// TODO TODO. /// </summary> /// <typeparam name="TMessage">TODO TMessage.</typeparam> /// <param name="recipient">TODO recipient.</param> /// <param name="token">TODO token.</param> /// <param name="action">TODO action.</param> /// <param name="lists">TODO lists.</param> private static void UnregisterFromLists <TMessage>(Object recipient, Object token, Action <TMessage> action, Dictionary <Type, List <WeakActionAndToken> > lists) { Type messageType = typeof(TMessage); if (recipient == null || lists == null || lists.Count == 0 || !lists.ContainsKey(messageType)) { return; } lock (lists) { foreach (WeakActionAndToken item in lists[messageType]) { WeakAction <TMessage> weakActionCasted = item.Action as WeakAction <TMessage>; if (weakActionCasted != null && recipient == weakActionCasted.Target && (action == null || action.Method.Name == weakActionCasted.MethodName) && (token == null || token.Equals(item.Token))) { item.Action.MarkForDeletion(); } } } }
public void TestStaticMethodWithNullTarget() { Reset(); var action = new WeakAction <string>(null, DoStuffStatic); Assert.IsTrue(action.IsAlive); }
private static void UnregisterFromLists(object recipient, Dictionary <Type, List <WeakActionAndToken> > lists) { if (recipient == null || lists == null || lists.Count == 0) { return; } lock (lists) { foreach (Type messageType in lists.Keys) { foreach (WeakActionAndToken item in lists[messageType]) { WeakAction weakAction = item.Action; if (weakAction != null && recipient == weakAction.Target) { weakAction.MarkForDeletion(); } } } } }
/// <summary> /// Registers a recipient for a type of message TMessage. /// The action parameter will be executed when a corresponding /// message is sent. See the receiveDerivedMessagesToo parameter /// for details on how messages deriving from TMessage (or, if TMessage is an interface, /// messages implementing TMessage) can be received too. /// <para>Registering a recipient does not create a hard reference to it, /// so if this recipient is deleted, no memory leak is caused.</para> /// </summary> /// <typeparam name="TMessage">The type of message that the recipient registers /// for.</typeparam> /// <param name="recipient">The recipient that will receive the messages.</param> /// <param name="token">A token for a messaging channel. If a recipient registers /// using a token, and a sender sends a message using the same token, then this /// message will be delivered to the recipient. Other recipients who did not /// use a token when registering (or who used a different token) will not /// get the message. Similarly, messages sent without any token, or with a different /// token, will not be delivered to that recipient.</param> /// <param name="receiveDerivedMessagesToo">If true, message types deriving from /// TMessage will also be transmitted to the recipient. For example, if a SendOrderMessage /// and an ExecuteOrderMessage derive from OrderMessage, registering for OrderMessage /// and setting receiveDerivedMessagesToo to true will send SendOrderMessage /// and ExecuteOrderMessage to the recipient that registered. /// <para>Also, if TMessage is an interface, message types implementing TMessage will also be /// transmitted to the recipient. For example, if a SendOrderMessage /// and an ExecuteOrderMessage implement IOrderMessage, registering for IOrderMessage /// and setting receiveDerivedMessagesToo to true will send SendOrderMessage /// and ExecuteOrderMessage to the recipient that registered.</para> /// </param> /// <param name="action">The action that will be executed when a message /// of type TMessage is sent.</param> public virtual void Register <TMessage>( object recipient, object token, bool receiveDerivedMessagesToo, Action <TMessage> action) { lock (_registerLock) { var messageType = typeof(TMessage); Dictionary <Type, List <WeakActionAndToken> > recipients; if (receiveDerivedMessagesToo) { if (_recipientsOfSubclassesAction == null) { _recipientsOfSubclassesAction = new Dictionary <Type, List <WeakActionAndToken> >(); } recipients = _recipientsOfSubclassesAction; } else { if (_recipientsStrictAction == null) { _recipientsStrictAction = new Dictionary <Type, List <WeakActionAndToken> >(); } recipients = _recipientsStrictAction; } lock (recipients) { List <WeakActionAndToken> list; if (!recipients.ContainsKey(messageType)) { list = new List <WeakActionAndToken>(); recipients.Add(messageType, list); } else { list = recipients[messageType]; } var weakAction = new WeakAction <TMessage>(recipient, action); var item = new WeakActionAndToken { Action = weakAction, Token = token }; list.Add(item); } } RequestCleanup(); }
public void TestNonClosureLambda() { var target = new TestClass(); var weakAction = new WeakAction <TestClass>(instance => instance.SetValue(3)); Assert.That(weakAction.Invoke(target), Is.True); Assert.That(target.Value, Is.EqualTo(3), "Value not updated on target"); }
public AutoRelayCommand(string executeMethodName, string canExecuteMethodName = null) { this.executeMethodName = executeMethodName; this.canExecuteMethodName = canExecuteMethodName; execute = new WeakAction(() => executeMethodInfo.Invoke(parentObject, null)); canExecute = new WeakFunc <bool>(() => (bool?)canExecuteMethodInfo.Invoke(parentObject, null) != false); }
public void TestNonClosureLambdaTwoParameters() { var target = new TestClass(); var weakAction = new WeakAction <TestClass, int>((instance, value) => instance.SetValue(value)); Assert.That(weakAction.Invoke(target, 3), Is.True); Assert.That(target.Value, Is.EqualTo(3), "Value not updated on target"); }
/// <summary>Initializes a new instance of the RelayCommand class.</summary> /// <param name="execute">The execution logic.</param> /// <param name="canExecute">The execution status logic.</param> /// <exception cref="T:System.ArgumentNullException">If the execute argument is null.</exception> public RelayCommand(Action <T> execute, Func <T, bool> canExecute) { this._execute = execute != null ? new WeakAction <T>(execute) : throw new ArgumentNullException(nameof(execute)); if (canExecute == null) { return; } this._canExecute = new WeakFunc <T, bool>(canExecute); }
public WeakAction <T> GetAction(WeakActionTestCase testCase) { WeakAction <T> action = null; switch (testCase) { case WeakActionTestCase.PublicNamedMethod: action = new WeakAction <T>( this, DoStuffPublically); break; case WeakActionTestCase.InternalNamedMethod: action = new WeakAction <T>( this, DoStuffInternally); break; case WeakActionTestCase.PrivateNamedMethod: action = new WeakAction <T>( this, DoStuffPrivately); break; case WeakActionTestCase.PublicStaticMethod: action = new WeakAction <T>( this, DoStuffPublicallyAndStatically); break; case WeakActionTestCase.InternalStaticMethod: action = new WeakAction <T>( this, DoStuffInternallyAndStatically); break; case WeakActionTestCase.PrivateStaticMethod: action = new WeakAction <T>( this, DoStuffPrivatelyAndStatically); break; case WeakActionTestCase.AnonymousStaticMethod: action = new WeakAction <T>( this, p => Result = Expected + p); break; case WeakActionTestCase.AnonymousMethod: action = new WeakAction <T>( this, p => Result = Expected + _index + p); break; } return(action); }
public void DisposeTest() { Action <string> action = _ => { }; var weakAction = new WeakAction <string>(action, KeepOwnerAliveMode.KeepAlive); weakAction.Dispose(); Assert.False(weakAction.IsAlive()); }
public RelayCommand(Action <T> execute, Func <T, bool> canExecute, IErrorHandler errorHandler) { this.execute = new WeakAction <T>(execute ?? throw new ArgumentNullException(nameof(execute))); this.errorHandler = errorHandler ?? throw new ArgumentNullException(nameof(errorHandler)); if (canExecute != null) { this.canExecute = new WeakFunc <T, bool>(canExecute); } }
public void WeakActionExecuteTestWithoutTarget() { StaticActionExecuted = false; var weakAction = new WeakAction(null, StaticActionExecute); weakAction.Execute(); Assert.True(StaticActionExecuted); }
public void WeakActionCtorTest() { var weakAction = new WeakAction(() => { }); var weakAction2 = new WeakAction(null, () => { }); weakAction.Execute(); weakAction2.Execute(); Assert.Throws <ArgumentNullException>(() => new WeakAction(null)); }
public void MemoryLeakFreeWithNoInvocation() { var target = new ActionTarget(); var weakAction = new WeakAction(target, target.PublicActionToExecute); target = null; GC.Collect(); Assert.IsFalse(weakAction.IsTargetAlive); }
public RelayCommand(Action execute, Func <bool> canExecute = null) { if (execute == null) { throw new ArgumentNullException(nameof(execute)); } _execute = new WeakAction(execute); _canExecute = new WeakFunc <bool>(canExecute); }
/// <summary> /// Initializes a new instance of the <see cref="Command{T}"/> class. /// </summary> /// <param name="execute">The execute.</param> /// <param name="canExecute">The can execute.</param> /// <param name="keepTargetAlive">if set to <c>true</c> [keep target alive].</param> /// <exception cref="ArgumentNullException">execute</exception> public Command(Action <T> execute, Func <T, bool> canExecute, bool keepTargetAlive = false) { Argument.IsNotNull(execute); _execute = new WeakAction <T>(execute, keepTargetAlive); if (canExecute is not null) { _canExecute = new WeakFunc <T, bool>(canExecute, keepTargetAlive); } }
public void WeakActionGenericCtorTest() { var iValue = 0; var weakAction = new WeakAction <int>(i => iValue = i); weakAction.Execute(10); Assert.True(iValue == 10); weakAction = new WeakAction <int>(i => _testOutputHelper.WriteLine(i.ToString())); weakAction.Execute(10); }
public void StaticMethodsAreSupported() { Action <Scaffold> staticMethod = Scaffold.SomeStaticMethod; var scaffold = new Scaffold(); var result = new WeakAction <Scaffold>(staticMethod); result.Invoke(scaffold); Assert.AreEqual(1, scaffold.InvokeCount); }
/// <summary> /// Gets the list of actions to be invoked for the specified message /// </summary> /// <param name="key">The message to get the actions for</param> /// <returns>Returns a list of actions that are registered to the specified message</returns> internal List <Delegate> GetActions(Type messageTargetType, string key) { if (key == null) { throw new ArgumentNullException("message"); } List <Delegate> actions; lock (_map) { if (!_map.ContainsKey(key)) { return(null); } List <WeakAction> weakActions = _map[key]; actions = new List <Delegate>(weakActions.Count); for (int i = weakActions.Count - 1; i > -1; --i) { WeakAction weakAction = weakActions[i]; if (weakAction == null) { continue; } if (weakAction.Recipient.GetType() == messageTargetType) { continue; } Delegate action = weakAction.CreateAction(); if (action != null) { actions.Add(action); } else { // The target object is dead, so get rid of the weak action. weakActions.Remove(weakAction); } } // Delete the list from the map if it is now empty. if (weakActions.Count == 0) { _map.Remove(key); } } // Reverse the list to ensure the callbacks are invoked in the order they were registered. actions.Reverse(); return(actions); }
public RelayCommand(Action execute, Func <bool> canExecute, bool keepTargetAlive = false) { if (execute == null) { throw new ArgumentNullException("execute"); } _execute = new WeakAction(execute, keepTargetAlive); if (canExecute != null) { _canExecute = new WeakFunc <bool>(canExecute, keepTargetAlive); } }
/// <summary> /// Initializes a new instance of the RelayCommand class. /// </summary> /// <param name="execute">The execution logic.</param> /// <param name="canExecute">The execution status logic.</param> /// <exception cref="T:System.ArgumentNullException">If the execute argument is null.</exception> public RelayCommand(Action execute, Func<bool> canExecute) { if (execute == null) { throw new ArgumentNullException("execute"); } this._execute = new WeakAction(execute); if (canExecute != null) { this._canExecute = new WeakFunc<bool>(canExecute); } }
public void WeakActionExecuteTest() { var actionExecuted = false; var weakAction = new WeakAction(() => actionExecuted = true); Assert.False(actionExecuted); weakAction.Execute(); Assert.True(actionExecuted); }
/// <summary> /// Initializes a new instance of the RelayCommand class. /// </summary> /// <param name="execute">The execution logic.</param> /// <param name="canExecute">The execution status logic.</param> /// <exception cref="T:System.ArgumentNullException">If the execute argument is null.</exception> public RelayCommand(Action execute, Func <bool> canExecute) { if (execute == null) { throw new ArgumentNullException("execute"); } this.execute = new WeakAction(execute); if (canExecute != null) { this.canExecute = new WeakFunc <bool>(canExecute); } }
public void TestSimple() { var target = new TestClass(); WeakAction <int> weakAction = new WeakAction <int>(target.SetValue); Assert.That(weakAction.Target, Is.Not.Null, "Target not set"); Assert.That(weakAction.IsAlive, Is.True, "Not alive"); Assert.That(weakAction.Method, Is.EqualTo(typeof(TestClass).GetMethod("SetValue"))); Assert.That(weakAction.Invoke(3), Is.True, "Invoke"); Assert.That(target.Value, Is.EqualTo(3)); }
public void NonGeneric_PublicMethod() { var target = new ActionTarget(); var weakAction = new WeakAction(target, target.PublicActionToExecute); Assert.IsTrue(weakAction.Execute()); Assert.AreEqual(1, target.PublicActionExecutedCount); target = null; GC.Collect(); Assert.IsFalse(weakAction.IsTargetAlive); }
/// <summary>实例化一个不可重入的定时器</summary> /// <param name="callback">委托</param> /// <param name="state">用户数据</param> /// <param name="dueTime">多久之后开始</param> /// <param name="period">间隔周期</param> /// <param name="usethreadpool">是否使用线程池。对于耗时短小且比较频繁的操作,不好使用线程池,减少线程切换。</param> public TimerX(WaitCallback callback, object state, int dueTime, int period, Boolean usethreadpool) { if (callback == null) throw new ArgumentNullException("callback"); if (dueTime < Timeout.Infinite) throw new ArgumentOutOfRangeException("dueTime"); if (period < Timeout.Infinite) throw new ArgumentOutOfRangeException("period"); Callback = new WeakAction<object>(callback); State = state; Period = period; UseThreadPool = usethreadpool; NextTime = DateTime.Now.AddMilliseconds(dueTime); TimerXHelper.Add(this); }
public void Generic_PublicMethod() { var target = new ActionTarget(); var weakAction = new WeakAction<int>(target, target.PublicActionWithParameterToExecute); Assert.IsTrue(weakAction.Execute(1)); Assert.AreEqual(1, target.PublicActionWithParameterExecutedCount); target = null; GC.Collect(); Assert.IsFalse(weakAction.IsTargetAlive); }