private CommandWrapper(Codon codon, IReadOnlyCollection<ICondition> conditions)
 {
     if (conditions == null)
         throw new ArgumentNullException("conditions");
     this.codon = codon;
     this.conditions = conditions;
     this.canExecuteChangedHandlersToRegisterOnCommand = new WeakCollection<EventHandler>();
 }
        //****************************************

        private void AllocateRange <TItem>(out WeakCollection <TItem> collection, int count) where TItem : class, new()
        {               //****************************************
            var Items = new TItem[count];

            //****************************************

            for (var Index = 0; Index < count; Index++)
            {
                Items[Index] = new TItem();
            }

            collection = new WeakCollection <TItem>();
            collection.AddRange(Items);
        }
        public void ClearWorksAfterCollect()
        {
            var wc = new WeakCollection <string>();

            {
                var a = new string('a', 1);
                wc.Add(a);
                Assert.Equal("a", wc.First());
            }
            GCEx.CollectAndWait();
            wc.Clear();
            Assert.Equal(0, wc.CapCount);
            Assert.False(wc.Any());
        }
        public void AddRange()
        {
            var MyCollection = new WeakCollection <object>();
            var MyObject1    = new object();
            var MyObject2    = new object();

            MyCollection.AddRange(new object[] { MyObject1, MyObject2 });

            GC.Collect();

            Assert.AreEqual(2, MyCollection.Count(), "Items were not added");

            GC.KeepAlive(MyObject1);
            GC.KeepAlive(MyObject2);
        }
        public void AddWorksAfterCollect()
        {
            var wc = new WeakCollection <string>();

            {
                wc.Add(new string('a', 1));
                Assert.Equal("a", wc.First());
            }
            GCEx.CollectAndWait();
            Assert.True(wc.CapCount <= 1);
            //Assert.Equal(0, wc.Count);
            wc.Add(new string('b', 1));
            Assert.Equal(1, wc.Count);
            Assert.Equal("b", wc.First());
        }
        public void RemoveWorksAfterCollect()
        {
            var arr = new[] { "a", "b" };
            var wc  = new WeakCollection <string>(arr);

            {
                wc.Add(new string('c', 1));
                wc.Add(new string('d', 1));
                wc.Add(new string('c', 1));
            }
            GCEx.CollectAndWait();
            Assert.False(wc.Remove("c"));
            Assert.False(wc.Remove("d"));
            Assert.True(wc.SequenceEqual(new[] { "a", "b" }));
        }
Exemple #7
0
        public Login(Database database, string user, string password)
        {
            this.database         = database;
            this.user             = user;
            this.password         = password;
            this.GlobalIdentifier = Guid.NewGuid();
            this.readOnly         = false;
            WeakCollectionSession session = new WeakCollectionSession
            {
                Name = "Sessions: " + database.Name
            };

            this.weakSessions = session;
            this.database.logins.Add(this);
        }
Exemple #8
0
 public void RegisterHandler(IChangedHandler handler)
 {
     lock (this)
     {
         if (_handlers == null)
         {
             _handlers = new WeakCollection <IChangedHandler>();
             _handlers.CleanedEvent += (sender, e) => { lock (this) if (_handlers.Count == 0)
                                                            {
                                                                _handlers = null;
                                                            }
             };
         }
         _handlers.Add(handler);
     }
 }
Exemple #9
0
 public void SetUp()
 {
     Object1        = new object();
     Object2        = new object();
     Object3        = new object();
     Object4        = new object();
     Object5        = new object();
     WeakCollection = new WeakCollection <object>
     {
         Object1,
         Object2,
         Object3,
         Object4,
         Object5
     };
 }
        public void CopyToWorksAfterCollect()
        {
            var arr = new[] { "a", "b" };
            var wc  = new WeakCollection <string>(arr);

            {
                wc.Add(new string('c', 1));
                wc.Add(new string('d', 1));
            }
            GCEx.CollectAndWait();
            var target = new string[5];

            wc.CopyTo(target, 1);
            Assert.True(arr.SequenceEqual(target.Skip(1).Take(2)));
            Assert.Null(target[0]);
            Assert.Null(target[3]);
            Assert.Null(target[4]);
        }
        public void ContainsWorksAfterCollect()
        {
            var arr = new[] { "a", "b" };
            var wc  = new WeakCollection <string>(arr);

            {
                wc.Add(new string('c', 1));
                wc.Add(new string('d', 1));
                Assert.True(wc.Contains("a"));
                Assert.True(wc.Contains("b"));
                Assert.True(wc.Contains("c"));
                Assert.True(wc.Contains("d"));
            }
            GCEx.CollectAndWait();
            Assert.True(wc.Contains("a"));
            Assert.True(wc.Contains("b"));
            Assert.False(wc.Contains("c"));
            Assert.False(wc.Contains("d"));
            Assert.False(wc.Contains("e"));
        }
Exemple #12
0
        /// <summary>
        /// Notifies all subscribed observers of the end of the sequence.
        /// </summary>
        public void OnCompleted()
        {
            IObserver <T>[] observers = null;
            lock (_gate)
            {
                ThrowIfDisposed();
                if (_observers != null)
                {
                    observers  = _observers.ToArray();
                    _observers = null;
                }
            }

            if (observers != null)
            {
                foreach (var observer in observers)
                {
                    observer.OnCompleted();
                }
            }
        }
        public void Cleanup()
        {
            WeakReference           WeakRef;
            WeakCollection <object> WeakCollection;

            {
                var StrongRef = new object();
                WeakRef        = new WeakReference(StrongRef);
                WeakCollection = new WeakCollection <object>()
                {
                    StrongRef
                };

                CollectionAssert.Contains(WeakCollection, StrongRef);
            }

            GC.Collect();
            GC.WaitForPendingFinalizers();

            Assert.IsNull(WeakRef.Target);
        }
Exemple #14
0
        private void EnsureCommandCreated()
        {
            if (!_commandCreated)
            {
                _commandCreated = true;
                _addInCommand   = CreateCommand(_codon);
                if (_canExecuteChangedHandlersToRegisterOnCommand != null)
                {
                    var handlers = _canExecuteChangedHandlersToRegisterOnCommand.ToArray();
                    _canExecuteChangedHandlersToRegisterOnCommand = null;

                    foreach (var handler in handlers)
                    {
                        if (_addInCommand != null)
                        {
                            _addInCommand.CanExecuteChanged += handler;
                        }
                        // Creating the command potentially changes the CanExecute state, so we should raise the event handlers once:
                        handler(this, EventArgs.Empty);
                    }
                }
            }
        }
        public void Clean()
        {
            var    c = new WeakCollection <object>();
            object x = new object();

            using (NoGCRegion.Enter(1000)) {
                c.Add(x);
                c.Add(x);
                c.Add(x);

                AddCollectableItems(c, 3);

                Assert.AreEqual(6, c.AddCountSinceLastClean);
                Assert.AreEqual(6, c.UnsafeCount);
            }

            Helpers.CollectAndWait();

            c.Clean();
            Assert.AreEqual(0, c.AddCountSinceLastClean);
            Assert.AreEqual(3, c.UnsafeCount);

            GC.KeepAlive(x);
        }
Exemple #16
0
 /// <summary>
 /// Initializes a new instance of the <see cref="WeakSubject{T}"/> class.
 /// </summary>
 public WeakSubject()
 {
     _observers = new WeakCollection <IObserver <T> >();
 }
Exemple #17
0
 protected Command(bool hookRequerySuggested)
 {
     this._hookRequerySuggested = hookRequerySuggested;
     this._weakHandlers         = new WeakCollection <EventHandler>();
 }
        /// <summary>
        /// Create a compiled delegate for the LightLambda, and saves it so
        /// future calls to Run will execute the compiled code instead of
        /// interpreting.
        /// </summary>
        internal void Compile(object state) {
            _compiled = LightLambdaClosureVisitor.BindLambda(_lambda, _closureVariables, out _delegateTypesMatch);

            // TODO: we can simplify this, and remove the weak references if we
            // have LightLambda.Run get the compiled delegate when it runs.

            // Get the list and replace it with null to free it.
            WeakCollection<LightLambda> list = _lightLambdas;
            lock (this) {
                _lightLambdas = null;
            }

            // Walk the list and set delegates for all of the lambdas
            foreach (LightLambda light in list) {
                light.Compiled = _compiled(light.Closure);
            }
        }
        //--------------------------------------------------------------
        #region Creation & Cleanup
        //--------------------------------------------------------------

        /// <summary>
        /// Initializes a new instance of the <see cref="ServiceContainer"/> class.
        /// </summary>
        public ServiceContainer()
        {
            _registry = new Dictionary<ServiceRegistration, ServiceEntry>();
            _childContainers = new WeakCollection<ServiceContainer>();

            // Register default services. (Needed for automatic parameter injection.)
            Register(typeof(IServiceProvider), null, container => container, CreationPolicy.LocalShared, DisposalPolicy.Manual);
            Register(typeof(IServiceLocator), null, container => container, CreationPolicy.LocalShared, DisposalPolicy.Manual);
            Register(typeof(ServiceContainer), null, container => container, CreationPolicy.LocalShared, DisposalPolicy.Manual);
        }
        public void Purge()
        {
            var weakCollection = new WeakCollection<object>();
              var list = new List<object>();
              object obj;
              for (int i = 0; i < 100; i++)
              {
            obj = i;
            list.Add(obj);
            weakCollection.Add(obj);
              }
              obj = null;

              for (int i = list.Count - 1; i >= 0; i--)
              {
            if (i % 2 == 0 || i % 3 == 0)
              list.RemoveAt(i);
              }

              GC.Collect();

              int index = 0;
              foreach (object item in weakCollection)
              {
            // Because of compiler/JIT optimization: The last element "99" might be
            // still be referenced by local variable and can't be purged.
            if (index == list.Count)
              continue;

            Assert.AreEqual(list[index], item);
            index++;
              }

              // WeakCollection<T> should be purged/compacted now.
              // --> Check again.
              index = 0;
              foreach (object item in weakCollection)
              {
            // Because of compiler/JIT optimization: The last element "99" might be
            // still be referenced by local variable and can't be purged.
            if (index == list.Count)
              continue;

            Assert.AreEqual(list[index], item);
            index++;
              }
        }
 public void SetUp()
 {
     Object1 = new object();
       Object2 = new object();
       Object3 = new object();
       Object4 = new object();
       Object5 = new object();
       WeakCollection = new WeakCollection<object>
       {
     Object1,
     Object2,
     Object3,
     Object4,
     Object5
       };
 }
        public void FinalizeWeakCollection()
        {
            Object2 = null;
              GC.Collect();

              WeakCollection = null;
              GC.Collect();
              GC.WaitForPendingFinalizers();
              GC.Collect();
        }
Exemple #23
0
        public void TestBasics()
        {
            WeakCollection<object> c = new WeakCollection<object>();
            c.Add(new object());
            c.Add(new object());
            c.Add(new object());
            c.Add(new object());
            c.Add(this);
            Assert.AreEqual(5, c.Count);
            Assert.IsTrue(c.Contains(this));
            int n = 0;
            foreach (object o in c)
            {
                Assert.IsTrue(o.GetType() == typeof(object) || o.GetType() == this.GetType());
                n++;
            }
            Assert.AreEqual(5, n);

            GC.Collect();
            GC.WaitForPendingFinalizers();

            Assert.AreEqual(1, c.Count);
            Assert.IsTrue(c.Contains(this));
            n = 0;
            foreach (object o in c)
            {
                Assert.IsTrue(o.GetType() == this.GetType());
                Assert.IsTrue(o == this);
                n++;
            }
            Assert.AreEqual(1, n);
            c.CopyTo(new object[1], 0);
        }
Exemple #24
0
 /// <summary>
 /// 创建一个 <typeparamref name="T"/> 的实例,然后加入到集合中。
 /// 必须调用这个方法创建,避免创建的局部变量被视为不能释放,详见:https://github.com/dotnet/runtime/issues/36265
 /// </summary>
 /// <typeparam name="T">要创建的实例的类型。</typeparam>
 /// <param name="collection">创建的实例加入到这个集合中。</param>
 private static void AddNewObject <T>(WeakCollection <T> collection) where T : class, new() => collection.Add(new T());
        /// <summary>
        /// Create a compiled delegate for the LightLambda, and saves it so
        /// future calls to Run will execute the compiled code instead of
        /// interpreting.
        /// </summary>
        internal void Compile(object state) {
            _compiled = LightLambdaClosureVisitor.BindLambda(_lambda, _closureVariables, out _delegateTypesMatch);

            // Get the list and replace it with null to free it.
            WeakCollection<LightLambda> list = _lightLambdas;
            lock (this) {
                _lightLambdas = null;
            }

            // Walk the list and set delegates for all of the lambdas
            foreach (LightLambda light in list) {
                light.Compiled = _compiled(light.Closure);
            }
        }
        void EnsureCommandCreated()
        {
            if (!commandCreated) {
                commandCreated = true;
                addInCommand = CreateCommand(codon);
                if (canExecuteChangedHandlersToRegisterOnCommand != null) {
                    var handlers = canExecuteChangedHandlersToRegisterOnCommand.ToArray();
                    canExecuteChangedHandlersToRegisterOnCommand = null;

                    foreach (var handler in handlers) {
                        if (addInCommand != null)
                            addInCommand.CanExecuteChanged += handler;
                        // Creating the command potentially changes the CanExecute state, so we should raise the event handlers once:
                        handler(this, EventArgs.Empty);
                    }
                }
            }
        }
Exemple #27
0
 protected Command()
 {
     this._weakHandlers = new WeakCollection <EventHandler>();
 }
Exemple #28
0
 private CommandWrapper(Codon codon, IReadOnlyCollection <ICondition> conditions)
 {
     _codon      = codon;
     _conditions = conditions ?? throw new ArgumentNullException(nameof(conditions));
     _canExecuteChangedHandlersToRegisterOnCommand = new WeakCollection <EventHandler>();
 }