Exemple #1
0
        public void DisposedOnIsValueCreatedTest()
        {
            var tl = new ThreadLocal <int>();

            tl.Dispose();
            GC.KeepAlive(tl.IsValueCreated);
        }
        public void Run()
        {
            var someDisposable = Substitute.For <IDisposable>();

            someDisposable.DidNotReceive().Dispose();

            var threadLocal = new ThreadLocal <IDisposable>(() => someDisposable);

            threadLocal.IsValueCreated.ShouldBeFalse();
            threadLocal.Value.ShouldBe(someDisposable);
            threadLocal.IsValueCreated.ShouldBeTrue();
            threadLocal.ToString().ShouldStartWith("Substitute.IDisposable|");
            threadLocal.Dispose();
            Should.Throw <ObjectDisposedException>(() => threadLocal.Value.ShouldBe(someDisposable))
            .Message.ShouldBe("Cannot access a disposed object.\r\nObject name: 'The ThreadLocal object has been disposed.'.");
            someDisposable.DidNotReceive().Dispose();

            var threadLocalDisposable = new ThreadLocalDisposable <IDisposable>(() => someDisposable);

            threadLocalDisposable.IsValueCreated.ShouldBeFalse();
            threadLocalDisposable.Value.ShouldBe(someDisposable);
            threadLocalDisposable.IsValueCreated.ShouldBeTrue();
            threadLocalDisposable.ToString().ShouldStartWith("Substitute.IDisposable|");
            threadLocalDisposable.Dispose();
            Should.Throw <ObjectDisposedException>(() => threadLocalDisposable.Value.ShouldBe(someDisposable))
            .Message.ShouldBe("Cannot access a disposed object.\r\nObject name: 'The ThreadLocal object has been disposed.'.");
            someDisposable.Received(1).Dispose();
        }
        private void Dispose(bool disposing)
        {
            if (_isDisposed)
            {
                return;
            }

            _timerSubscription?.Dispose();
            _meterInformation.Dispose();
            _simpleAudioVolume.Dispose();
            _deviceMutedSubscription.Dispose();
            _muteChanged.Dispose();
            _stateChanged.Dispose();
            _disconnected.Dispose();
            _volumeChanged.Dispose();
            _peakValueChanged.Dispose();


            //Run this on the com thread to ensure it's disposed correctly
            ComThread.BeginInvoke(() =>
            {
                AudioSessionControl.UnregisterAudioSessionNotification(this);
            }).ContinueWith(x =>
            {
                _audioSessionControl.Dispose();
            });

            GC.SuppressFinalize(this);
            _isDisposed = true;
        }
Exemple #4
0
        //~FileManager()
        //{
        //    Dispose();
        //}

        public void Dispose()
        {
            foreach (var viewWrap in _allWraps)
            {
                viewWrap._va.Dispose();
            }
            _vw.Dispose();

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

            try {
                FileMutex.WaitOne();
                CloseMapFile();
                if (PersistenceMode == PersistenceMode.TemporaryPersist)
                {
                    var count = _tempSemaphore.Release();
                    // if no more access to the file, then delete it
                    if (count == _MAX_SHARED_ACCESS - 1)
                    {
                        DeleteBackingFileIfExists(_fileName);
                    }
                    _tempSemaphore.Dispose();
                }
            } finally {
                FileMutex.ReleaseMutex();
            }

            FileMutex.Dispose();
        }
Exemple #5
0
 public void Dispose()
 {
     _localCommitted.Dispose();
     _localDeletedCollection.Dispose();
     _localModifiedCollection.Dispose();
     _localNewCollection.Dispose();
 }
Exemple #6
0
        private void DisposeWindows(bool isDisposing)
        {
            AssertDisposing(_state);

            if (isDisposing)
            {
                var threadWindows = _windows.Values;

                for (var i = 0; i < threadWindows.Count; i++)
                {
                    var windows = threadWindows[i];

                    if (windows != null)
                    {
                        var hWnds = windows.Keys;

                        foreach (var hWnd in hWnds)
                        {
                            var dispatchProvider = Win32DispatchProvider.Instance;
                            var window           = RemoveWindow(windows, hWnd);
                            window.Dispose();
                        }

                        Assert(AssertionsEnabled && (windows.Count == 0));
                    }
                }

                _windows.Dispose();
            }
        }
 protected override void Dispose(bool disposing)
 {
     _committed.Dispose();
     _newEntities.Dispose();
     _modifiedEntities.Dispose();
     _deletedEntities.Dispose();
 }
 public override void Dispose()
 {
     adjacentSimsTL.Dispose();
     lerpLeftRightTL.Dispose();
     lerpTopBotTL.Dispose();
     base.Dispose();
 }
Exemple #9
0
        public void Dispose()
        {
            disposerLock.EnterWriteLock();
            try
            {
                if (databasesCleanupTimer != null)
                {
                    databasesCleanupTimer.Dispose();
                }
                if (listener != null && listener.IsListening)
                {
                    listener.Stop();
                }

                disposed = true;

                lock (ResourcesStoresCache)
                {
                    foreach (var documentDatabase in ResourcesStoresCache)
                    {
                        documentDatabase.Value.Dispose();
                    }
                    ResourcesStoresCache.Clear();
                }

                currentConfiguration.Dispose();
                currentDatabase.Dispose();
                currentTenantId.Dispose();
            }
            finally
            {
                disposerLock.ExitWriteLock();
            }
        }
        protected virtual void Dispose(bool disposing)
        {
            if (disposing)
            {
                foreach (var viewWrap in _allWraps)
                {
                    viewWrap._va.Dispose();
                }
                _vw.Dispose();
            }

            try {
                FileMutex.WaitOne();
                CloseMapFile();
                if (PersistenceMode == PersistenceMode.TemporaryPersist)
                {
                    var count = _tempSemaphore.Release();
                    // if no more access to the file, then delete it
                    if (count == _MAX_SHARED_ACCESS - 1)
                    {
                        DeleteBackingFileIfExists(_fileName);
                    }
                    _tempSemaphore.Dispose();
                }
            } finally {
                FileMutex.ReleaseMutex();
            }

            FileMutex.Dispose();
        }
Exemple #11
0
        public void DisposedOnValueTest()
        {
            var tl = new ThreadLocal <int>();

            tl.Dispose();
            GC.KeepAlive(tl.Value);
        }
Exemple #12
0
 public void Dispose()
 {
     shouldNotifyOnWork.Dispose();
     if (DocsPerSecCounter != null)
     {
         DocsPerSecCounter.Dispose();
     }
     if (ReducedPerSecCounter != null)
     {
         ReducedPerSecCounter.Dispose();
     }
     if (RequestsPerSecCounter != null)
     {
         RequestsPerSecCounter.Dispose();
     }
     if (ConcurrentRequestsCounter != null)
     {
         ConcurrentRequestsCounter.Dispose();
     }
     if (IndexedPerSecCounter != null)
     {
         IndexedPerSecCounter.Dispose();
     }
     cancellationTokenSource.Dispose();
 }
Exemple #13
0
        /// <summary>
        /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
        /// </summary>
        /// <filterpriority>2</filterpriority>
        public void Dispose()
        {
            ThreadLocal <List <T> > local = _local;

            if (local == null)
            {
                return;
            }

            if (_values != null)
            {
                return;
            }

            Debug.Assert(local.Values != null);
            T[] values = local.Values.SelectMany(l => l).ToArray();

            if (_values != null)
            {
                return;
            }

            _values = values;

            _local = null;
            local.Dispose();
        }
Exemple #14
0
 public void Dispose()
 {
     _localCommitted.Dispose();
     _localDeletedList.Dispose();
     _localModifiedList.Dispose();
     _localNewList.Dispose();
 }
Exemple #15
0
        /// <summary>
        ///   Releases unmanaged and - optionally - managed resources
        /// </summary>
        /// 
        /// <param name="disposing"><c>true</c> to release both managed 
        /// and unmanaged resources; <c>false</c> to release only unmanaged
        /// resources.</param>
        /// 
        protected virtual void Dispose(bool disposing)
        {
            if (disposing)
            {
                // free managed resources
                if (inputs != null)
                    inputs.Dispose();
                if (outputs != null)
                    outputs.Dispose();
                if (logLikelihoods != null)
                    logLikelihoods.Dispose();
                if (gradient != null)
                    gradient.Dispose();
                if (lnZx != null)
                    lnZx.Dispose();
                if (lnZxy != null)
                    lnZxy.Dispose();
                if (error != null)
                    error.Dispose();

                inputs = null;
                outputs = null;
                gradient = null;
                logLikelihoods = null;
                lnZxy = null;
                lnZx = null;
                error = null;
            }
        }
 public void Dispose()
 {
     disposerLock.EnterWriteLock();
     try
     {
         if (disposed)
         {
             return;
         }
         disposed = true;
         current.Dispose();
         if (documentCacher != null)
         {
             documentCacher.Dispose();
         }
         if (idleTimer != null)
         {
             idleTimer.Dispose();
         }
         if (persistenceSource != null)
         {
             persistenceSource.Dispose();
         }
         if (tableStroage != null)
         {
             tableStroage.Dispose();
         }
     }
     finally
     {
         disposerLock.ExitWriteLock();
     }
 }
        public MainWindow()
        {
            InitializeComponent();
            ThreadLocal <string> threadName = new ThreadLocal <string>(() =>
            {
                return("Thread" + Thread.CurrentThread.ManagedThreadId);
            });

            Action action = () =>
            {
                bool repeat = threadName.IsValueCreated;

                tb.Text = string.Format("ThreadName = {0} {1}", threadName.Value, repeat ? "(repeat)" : "");
            };

            Parallel.Invoke(action, action, action, action);
            threadName.Dispose();

            //List<string> vs = new List<string>
            //{
            //	"abc",
            //	"def"
            //};
            //var vb = vs.Select(x => x != null);
        }
Exemple #18
0
        private void DisposeWindows(bool isDisposing)
        {
            AssertDisposing(_state);

            if (isDisposing)
            {
                var threadWindows = _windows.Values;

                for (var i = 0; i < threadWindows.Count; i++)
                {
                    var windows = threadWindows[i];

                    if (windows is not null)
                    {
                        var windowHandles = windows.Keys;

                        foreach (var windowHandle in windowHandles)
                        {
                            var dispatchService = XlibDispatchService.Instance;
                            var window          = RemoveWindow(windows, dispatchService.Display, windowHandle, dispatchService);
                            window.Dispose();
                        }

                        Assert(AssertionsEnabled && (windows.Count == 0));
                    }
                }

                _windows.Dispose();
            }
        }
Exemple #19
0
        /// <summary>
        /// Release any contained resources.
        /// </summary>
        /// <param name="disposing">set this to true if releasing managed resources</param>
        protected virtual void Dispose(bool disposing)
        {
            if (!disposing)
            {
                return;
            }

            if (!m_ownPoller && !m_poller.IsStarted)
            {
                DisposeSynced();
                return;
            }

            // disposing on the scheduler thread
            var task = new Task(DisposeSynced);

            task.Start(this);
            task.Wait();

            // poller cannot be stopped from poller thread
            if (m_ownPoller)
            {
                m_poller.CancelAndJoin();
                m_poller.Dispose();
            }
            m_schedulerThread.Dispose();
        }
Exemple #20
0
        /// <summary>
        /// Reset cached value
        /// </summary>
        /// <remarks>
        /// Resets the cache for all threads
        /// </remarks>
        public void ResetCache()
        {
            ThreadLocal <CacheEntry> oldCacheEntry = this.localCacheEntry;

            this.localCacheEntry = new ThreadLocal <CacheEntry>();
            oldCacheEntry?.Dispose();
        }
Exemple #21
0
        public void DisposedOnValueTest()
        {
            var tl = new ThreadLocal <int> ();

            tl.Dispose();
            var value = tl.Value;
        }
Exemple #22
0
 /// <summary>
 /// Disposing.
 /// </summary>
 /// <param name="disposing"></param>
 protected virtual void Dispose(bool disposing)
 {
     if (_randomGen != null && _randomGen.IsValueCreated && _randomGen.Value != null)
     {
         _randomGen.Dispose();
     }
 }
        public void Dispose()
        {
            disposerLock.EnterWriteLock();
            try
            {
                if (disposed)
                {
                    return;
                }

                disposed = true;

                var exceptionAggregator = new ExceptionAggregator("Could not properly dispose TransactionalStorage");

                exceptionAggregator.Execute(() => current.Dispose());

                if (tableStorage != null)
                {
                    exceptionAggregator.Execute(() => tableStorage.Dispose());
                }

                if (bufferPool != null)
                {
                    exceptionAggregator.Execute(() => bufferPool.Dispose());
                }

                exceptionAggregator.ThrowIfNeeded();
            }
            finally
            {
                disposerLock.ExitWriteLock();
            }
        }
Exemple #24
0
        static void Main(string[] args)
        {
            //var test = new ThreadLocal<Test>(() =>
            //    { return new Test(); }
            //);
            var    test    = new ThreadLocal <ITest>(trackAllValues: true);
            Action actionA = () =>
            {
                test.Value = new TestA();
                //Console.WriteLine($"The test id is {test.Value.Id}");
            };

            Action actionB = () =>
            {
                test.Value = new TestB();
            };

            //Action action = () =>
            //      {
            //          //bool isCreated = threadName.IsValueCreated;
            //          //Console.WriteLine(threadName.Value + (isCreated ? ("Repeated"):""));
            //          //number.Value = Guid.NewGuid();
            //          Console.WriteLine($"{test.Value.Id} threadId is: {Thread.CurrentThread.ManagedThreadId}.");
            //      };

            Parallel.Invoke(actionA, actionB, actionB, actionA, actionB, actionA, actionA, actionB, actionB);
            test.Values.ToList().ForEach(v => Console.WriteLine(v.GetType()));
            test.Dispose();
            Console.Read();
        }
        public void DisposedOnIsValueCreatedTest()
        {
            var tl = new ThreadLocal <int> ();

            tl.Dispose();
            var value = tl.IsValueCreated;
        }
Exemple #26
0
        private void DisposeWindows(bool isDisposing)
        {
            _state.AssertDisposing();

            if (isDisposing)
            {
                var threadWindows = _windows.Values;

                for (var i = 0; i < threadWindows.Count; i++)
                {
                    var windows = threadWindows[i];

                    if (windows != null)
                    {
                        var windowHandles = windows.Keys;

                        foreach (var windowHandle in windowHandles)
                        {
                            var dispatchProvider = UI.DispatchProvider.Instance;
                            var window           = RemoveWindow(windows, dispatchProvider.Display, windowHandle, dispatchProvider);
                            window.Dispose();
                        }

                        Assert(windows.Count == 0, Resources.ArgumentOutOfRangeExceptionMessage, nameof(windows.Count), windows.Count);
                    }
                }

                _windows.Dispose();
            }
        }
Exemple #27
0
 internal static void Dispose()
 {
     CachedGuidBuffer.Values.ForEach(Marshal.FreeHGlobal);
     Current.Dispose();
     Cache.Dispose();
     CacheManagedOnly.Dispose();
 }
        public void Dispose()
        {
            disposerLock.EnterWriteLock();
            try
            {
                if (disposed)
                {
                    return;
                }
                disposed = true;
                current.Dispose();

                if (tableStorage != null)
                {
                    tableStorage.Dispose();
                }

                if (bufferPool != null)
                {
                    bufferPool.Dispose();
                }
            }
            finally
            {
                disposerLock.ExitWriteLock();
            }
        }
Exemple #29
0
 /// <summary>
 /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
 /// </summary>
 public void Dispose()
 {
     _shouldStop = true;
     WorkExists();
     _workerThread.Join();
     _canary.Dispose();
 }
Exemple #30
0
        internal void Clear(bool dispose)
        {
            lock (AllSubscriptions)
            {
                if (_disposed)
                {
                    return;
                }

                AllSubscriptions.Clear();

                for (var i = 0; i < _localSubscriptions.Values.Count; i++)
                {
                    _localSubscriptions.Values[i].Clear();
                }

                if (dispose)
                {
                    _localSubscriptionRevision.Dispose();
                    _localSubscriptions.Dispose();
                    _disposed = true;
                }
                else
                {
                    _subscriptionsChangeCounter++;
                }
            }
        }
        public void PlayWithThreadLocal()
        {
            var threadName = new ThreadLocal<string>(() => Thread.CurrentThread.ManagedThreadId.ToString());
            Action action = () =>
            {
                var repeat = threadName.IsValueCreated ? "(repeat)" : "";
                var name = threadName.Value;
                Console.Out.WriteLine("name = {0} {1}", name, repeat);
            };

            Parallel.Invoke(action, action, action, action, action, action, action, action);

            threadName.Dispose();
        }
 public void DisposedOnValueTest()
 {
     var tl = new ThreadLocal<int>();
     tl.Dispose();
     var value = tl.Value;
 }
 public void DisposedOnIsValueCreatedTest()
 {
     var tl = new ThreadLocal<int>();
     tl.Dispose();
     var value = tl.IsValueCreated;
 }
Exemple #34
0
        private static bool RunThreadLocalTest5_Dispose()
        {
            TestHarness.TestLog("* RunThreadLocalTest5_Dispose()");

            ThreadLocal<string> tl = new ThreadLocal<string>(() => "dispose test");
            string value = tl.Value;

            tl.Dispose();

            if (!TestHarnessAssert.EnsureExceptionThrown(() => { string tmp = tl.Value; }, typeof(ObjectDisposedException), "The Value property of the disposed ThreadLocal object should throw ODE"))
                return false;

            if (!TestHarnessAssert.EnsureExceptionThrown(() => { bool tmp = tl.IsValueCreated; }, typeof(ObjectDisposedException), "The IsValueCreated property of the disposed ThreadLocal object should throw ODE"))
                return false;

            if (!TestHarnessAssert.EnsureExceptionThrown(() => { string tmp = tl.ToString(); }, typeof(ObjectDisposedException), "The ToString method of the disposed ThreadLocal object should throw ODE"))
                return false;


            // test recycling the combination index;

            tl = new ThreadLocal<string>(() => null);
            if(tl.IsValueCreated)
            {
                TestHarness.TestLog("* Filed, reusing the same index kept the old value and didn't use the new value.");
                return false;
            }
            if (tl.Value != null)
            {
                TestHarness.TestLog("* Filed, reusing the same index kept the old value and didn't use the new value.");
                return false;
            }


            return true;
        }
Exemple #35
0
        private static void RunThreadLocalTest8Helper(ManualResetEventSlim mres)
        {
            var tl = new ThreadLocal<object>(true);
            var t = Task.Run(() => tl.Value = new SetMreOnFinalize(mres));
            t.Wait();
            t = null;
            GC.Collect();
            GC.WaitForPendingFinalizers();
            GC.Collect();
            Assert.True(tl.Values.Count == 1, "RunThreadLocalTest8_Values: Expected other thread to have set value");
            Assert.True(tl.Values[0] is SetMreOnFinalize, "RunThreadLocalTest8_Values: Expected other thread's value to be of the right type");
            tl.Dispose();

            object values;
            Assert.Throws<ObjectDisposedException>(() => values = tl.Values);
        }
Exemple #36
0
        public static void RunThreadLocalTest8_Values()
        {
            // Test adding values and updating values
            {
                var threadLocal = new ThreadLocal<int>(true);
                Assert.True(threadLocal.Values.Count == 0, "RunThreadLocalTest8_Values: Expected thread local to initially have 0 values");
                Assert.True(threadLocal.Value == 0, "RunThreadLocalTest8_Values: Expected initial value of 0");
                Assert.True(threadLocal.Values.Count == 1, "RunThreadLocalTest8_Values: Expected values count to now be 1 from initialized value");
                Assert.True(threadLocal.Values[0] == 0, "RunThreadLocalTest8_Values: Expected values to contain initialized value");

                threadLocal.Value = 42;
                Assert.True(threadLocal.Values.Count == 1, "RunThreadLocalTest8_Values: Expected values count to still be 1 after updating existing value");
                Assert.True(threadLocal.Values[0] == 42, "RunThreadLocalTest8_Values: Expected values to contain updated value");

                ((IAsyncResult)Task.Run(() => threadLocal.Value = 43)).AsyncWaitHandle.WaitOne();
                Assert.True(threadLocal.Values.Count == 2, "RunThreadLocalTest8_Values: Expected values count to be 2 now that another thread stored a value");
                Assert.True(threadLocal.Values.Contains(42) && threadLocal.Values.Contains(43), "RunThreadLocalTest8_Values: Expected values to contain both thread's values");

                int numTasks = 1000;
                Task[] allTasks = new Task[numTasks];
                for (int i = 0; i < numTasks; i++)
                {
                    // We are creating the task using TaskCreationOptions.LongRunning because...
                    // there is no guarantee that the Task will be created on another thread.
                    // There is also no guarantee that using this TaskCreationOption will force
                    // it to be run on another thread.
                    var task = Task.Factory.StartNew(() => threadLocal.Value = i, CancellationToken.None, TaskCreationOptions.LongRunning, TaskScheduler.Default);
                    task.Wait();
                }

                var values = threadLocal.Values;
                Assert.True(values.Count == 1002, "RunThreadLocalTest8_Values: Expected values to contain both previous values and 1000 new values");
                for (int i = 0; i < 1000; i++)
                {
                    Assert.True(values.Contains(i), "RunThreadLocalTest8_Values: Expected values to contain value for thread #: " + i);
                }

                threadLocal.Dispose();
            }

            // Test that thread values remain after threads depart
            {
                var tl = new ThreadLocal<string>(true);
                var t = Task.Run(() => tl.Value = "Parallel");
                t.Wait();
                t = null;
                GC.Collect();
                GC.WaitForPendingFinalizers();
                GC.Collect();
                Assert.True(tl.Values.Count == 1, "RunThreadLocalTest8_Values: Expected values count to be 1 from other thread's initialization");
                Assert.True(tl.Values.Contains("Parallel"), "RunThreadLocalTest8_Values: Expected values to contain 'Parallel'");
            }
        }
Exemple #37
0
        public static void RunThreadLocalTest5_Dispose_Negative()
        {
            ThreadLocal<string> tl = new ThreadLocal<string>(() => "dispose test");
            string value = tl.Value;

            tl.Dispose();

            Assert.Throws<ObjectDisposedException>(() => { string tmp = tl.Value; });
            // Failure Case: The Value property of the disposed ThreadLocal object should throw ODE

            Assert.Throws<ObjectDisposedException>(() => { bool tmp = tl.IsValueCreated; });
            // Failure Case: The IsValueCreated property of the disposed ThreadLocal object should throw ODE

            Assert.Throws<ObjectDisposedException>(() => { string tmp = tl.ToString(); });
            // Failure Case: The ToString method of the disposed ThreadLocal object should throw ODE

        }