Ejemplo n.º 1
0
        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
        }
Ejemplo n.º 2
0
        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
        }
Ejemplo n.º 4
0
        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);
        }
Ejemplo n.º 8
0
        /// <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();
                    }
                }
            }
        }
Ejemplo n.º 9
0
        public void TestStaticMethodWithNullTarget()
        {
            Reset();
            var action = new WeakAction <string>(null, DoStuffStatic);

            Assert.IsTrue(action.IsAlive);
        }
Ejemplo n.º 10
0
        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();
                        }
                    }
                }
            }
        }
Ejemplo n.º 11
0
        /// <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();
        }
Ejemplo n.º 12
0
        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");
        }
Ejemplo n.º 13
0
        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);
        }
Ejemplo n.º 14
0
        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");
        }
Ejemplo n.º 15
0
 /// <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);
 }
Ejemplo n.º 16
0
        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);
        }
Ejemplo n.º 17
0
        public void DisposeTest()
        {
            Action <string> action     = _ => { };
            var             weakAction = new WeakAction <string>(action, KeepOwnerAliveMode.KeepAlive);

            weakAction.Dispose();

            Assert.False(weakAction.IsAlive());
        }
Ejemplo n.º 18
0
 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);
     }
 }
Ejemplo n.º 19
0
        public void WeakActionExecuteTestWithoutTarget()
        {
            StaticActionExecuted = false;
            var weakAction = new WeakAction(null, StaticActionExecute);

            weakAction.Execute();

            Assert.True(StaticActionExecuted);
        }
Ejemplo n.º 20
0
        public void WeakActionCtorTest()
        {
            var weakAction  = new WeakAction(() => { });
            var weakAction2 = new WeakAction(null, () => { });

            weakAction.Execute();
            weakAction2.Execute();

            Assert.Throws <ArgumentNullException>(() => new WeakAction(null));
        }
Ejemplo n.º 21
0
        public void MemoryLeakFreeWithNoInvocation()
        {
            var target     = new ActionTarget();
            var weakAction = new WeakAction(target, target.PublicActionToExecute);

            target = null;
            GC.Collect();

            Assert.IsFalse(weakAction.IsTargetAlive);
        }
Ejemplo n.º 22
0
        public void MemoryLeakFreeWithNoInvocation()
        {
            var target = new ActionTarget();
            var weakAction = new WeakAction(target, target.PublicActionToExecute);

            target = null;
            GC.Collect();

            Assert.IsFalse(weakAction.IsTargetAlive);
        }
Ejemplo n.º 23
0
        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);
        }
Ejemplo n.º 24
0
        /// <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);
            }
        }
Ejemplo n.º 25
0
        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);
        }
Ejemplo n.º 26
0
        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);
        }
Ejemplo n.º 27
0
            /// <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);
            }
Ejemplo n.º 28
0
 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);
     }
 }
Ejemplo n.º 29
0
 /// <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);
     }
 }
Ejemplo n.º 30
0
        public void WeakActionExecuteTest()
        {
            var actionExecuted = false;

            var weakAction = new WeakAction(() => actionExecuted = true);

            Assert.False(actionExecuted);

            weakAction.Execute();

            Assert.True(actionExecuted);
        }
Ejemplo n.º 31
0
 /// <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);
     }
 }
Ejemplo n.º 32
0
        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));
        }
Ejemplo n.º 33
0
        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);
        }
Ejemplo n.º 34
0
        /// <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);
        }
Ejemplo n.º 35
0
        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);
        }