System.Threading.Monitor.Exit(object)

Here are the examples of the csharp api System.Threading.Monitor.Exit(object) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

802 Examples 7

19 View Source File : Channel.cs
License : Apache License 2.0
Project Creator : apache

public void Dispose()
            => Monitor.Exit(_lock);

19 View Source File : SimpleMetricsSink.cs
License : Apache License 2.0
Project Creator : awslabs

private void Flush(object state)
        {
            //Wait maximum half of the interval _interval * 1000/2
            if (Monitor.TryEnter(_flushTimer, _interval * 500))
            {
                try
                {
                    IDictionary<MetricKey, MetricValue> acreplacedulatedValues = null;
                    IDictionary<MetricKey, MetricValue> lastValues = null;
                    lock (this)
                    {
                        acreplacedulatedValues = _acreplacedulatedValues;
                        _acreplacedulatedValues = InitAcreplacedulatedValues();
                        lastValues = new Dictionary<MetricKey, MetricValue>(_lastValues);
                    }
                    OnFlush(acreplacedulatedValues, lastValues);
                }
                catch (Exception ex)
                {
                    _logger?.LogError($"Metrics sink flush error id {Id} exception: {ex.ToMinimized()}");
                }
                finally
                {
                    Monitor.Exit(_flushTimer);
                }
            }
        }

19 View Source File : BlockingLambdaSubscriber.cs
License : Apache License 2.0
Project Creator : akarnokd

void Unblock()
        {
            if (Interlocked.Increment(ref wip) == 1)
            {
                Monitor.Enter(this);
                Monitor.Pulse(this);
                Monitor.Exit(this);
            }
        }

19 View Source File : DownloaderViewModel.cs
License : GNU General Public License v3.0
Project Creator : antikmozib

private async Task RemoveObjectsAsync(bool delete, params DownloaderObjectModel[] objects)
        {
            await _semapreplacedUpdatingList.WaitAsync();

            var dequeueThese = new List<IQueueable>();
            var itemsProcessed = new List<DownloaderObjectModel>();
            var total = objects.Count();
            _ctsUpdatingList = new CancellationTokenSource();
            var ct = _ctsUpdatingList.Token;
            RaisePropertyChanged(nameof(this.IsBackgroundWorking));
            int progress;
            string primaryStatus = "Removing ";
            if (delete) primaryStatus = "Deleting ";
            for (int i = 0; i < total; i++)
            {
                progress = (int)((double)(i + 1) / total * 100);
                this.Status = primaryStatus + (i + 1) + " of " + total + ": " + objects[i].Name;
                this.Progress = progress;
                RaisePropertyChanged(nameof(this.Status));
                RaisePropertyChanged(nameof(this.Progress));

                if (objects[i] == null) continue;

                if (objects[i].IsQueued)
                {
                    objects[i].Dequeue();
                    dequeueThese.Add(objects[i]);
                }

                if (objects[i].IsBeingDownloaded)
                {
                    await objects[i].CancelAsync();
                }
                else
                {
                    // delete all UNFINISHED downloads forcefully
                    if (objects[i].Status != DownloadStatus.Finished || delete)
                    {
                        try
                        {
                            if (objects[i].Status == DownloadStatus.Finished)
                            {
                                FileSystem.DeleteFile(
                                    objects[i].Destination,
                                    UIOption.OnlyErrorDialogs,
                                    RecycleOption.SendToRecycleBin);
                            }
                            else
                            {
                                File.Delete(objects[i].TempDestination);
                            }
                        }
                        catch { }
                    }
                }

                itemsProcessed.Add(objects[i]);

                if (ct.IsCancellationRequested)
                {
                    break;
                }
            }

            this.Status = "Delisting...";
            RaisePropertyChanged(nameof(this.Status));

            Application.Current.Dispatcher.Invoke(() =>
            {
                Monitor.Enter(_lockDownloadItemsList);
                for (int i = 0; i < itemsProcessed.Count(); i++)
                {
                    DownloadItemsList.Remove(itemsProcessed[i]);
                }
                Monitor.Exit(_lockDownloadItemsList);
            });

            if (dequeueThese.Count > 0)
            {
                this.Status = "Refreshing queue...";
                RaisePropertyChanged(nameof(this.Status));
                QueueProcessor.Remove(dequeueThese.ToArray());
            }

            _ctsUpdatingList = null;
            this.Status = "Ready";
            this.Progress = 0;
            RaisePropertyChanged(nameof(this.Status));
            RaisePropertyChanged(nameof(this.Progress));
            RaisePropertyChanged(nameof(this.IsBackgroundWorking));
            _semapreplacedUpdatingList.Release();
        }

19 View Source File : BlockingQueueConsumer.cs
License : Apache License 2.0
Project Creator : akarnokd

internal void Run()
        {
            Thread.CurrentThread.IsBackground = daemon;
            var n = name;
            if (n != null)
            {
                try 
                { 
                    Thread.CurrentThread.Name = n;
                }
                catch (InvalidOperationException)
                {
                    // ignored
                }
            }
            var sh = ShutdownAction;
            var q = queue;
            long missed = 0L;
            for (;;)
            {
                if (Volatile.Read(ref shutdown) != 0)
                {
                    q.Clear();
                    break;
                }
                Action a = null;

                for (int i = 0; i < 64; i++)
                {
                    if (q.Poll(out a))
                    {
                        break;
                    }
                }

                if (a != null)
                {
                    if (a == sh)
                    {
                        q.Clear();
                        break;
                    }
                    try
                    {
                        a();
                    }
                    catch
                    {
                        // TODO what to do with these?
                    }
                }
                else
                {
                    long w = Volatile.Read(ref wip);
                    if (w == missed)
                    {
                        missed = Interlocked.Add(ref wip, -missed);
                        if (missed == 0)
                        {
                            if (Monitor.TryEnter(this))
                            {
                                try
                                {
                                    while ((missed = Volatile.Read(ref wip)) == 0)
                                    {
                                        Monitor.Wait(this);
                                    }
                                }
                                finally
                                {
                                    Monitor.Exit(this);
                                }
                            }
                        }
                    }
                    else
                    {
                        missed = w;
                    }
                }
            }
        }

19 View Source File : BaseShimHandler.cs
License : Mozilla Public License 2.0
Project Creator : agebullhu

public void Run(PairSocket shim)
        {
            string shimAdd = $"inproc://wsrouter-{Id}";
            Monitor.Enter(this);
            try
            {
                isRuning = true;
                shim.SignalOK();

                shim.ReceiveReady += OnShimReady;

                MessagesPipe = new PairSocket();
                MessagesPipe.Connect(shimAdd);
                MessagesPipe.ReceiveReady += OnMessagePipeReady;

                Stream = new StreamSocket();
                Stream.Bind(Address);
                Stream.ReceiveReady += OnStreamReady;

                Poller = new NetMQPoller
                {
                    MessagesPipe,
                    shim,
                    Stream
                };
                MessagesPipe.SignalOK();
                Poller.Run();
                shim.Dispose();
            }
            catch(Exception ex)
            {
                Console.WriteLine(ex);
            }
            finally
            {
                Monitor.Exit(this);
            }
        }

19 View Source File : DriverPool.cs
License : Apache License 2.0
Project Creator : atata-framework

public static RemoteWebDriver Acquire(IDriverFactory driverFactory, object poolScopeObject = null)
        {
            if (driverFactory == null)
                throw new ArgumentNullException(nameof(driverFactory));

            ConcurrentBag<DriverEntry> entries = ResolveEntriesBag(poolScopeObject);

            Monitor.Enter(entries);

            try
            {
                DriverEntry entry = entries.FirstOrDefault(x => x.Alias == driverFactory.Alias && !x.IsAcquired);

                if (entry is null)
                {
                    Monitor.Exit(entries);

                    entry = CreateDriverEntry(driverFactory);
                    entry.IsAcquired = true;

                    entries.Add(entry);
                }
                else
                {
                    entry.IsAcquired = true;
                }

                return entry.Driver;
            }
            finally
            {
                if (Monitor.IsEntered(entries))
                    Monitor.Exit(entries);
            }
        }

19 View Source File : RedisProxy.Core.cs
License : Mozilla Public License 2.0
Project Creator : agebullhu

public void Dispose()
        {
            if (connect == null)
                return;
            Monitor.Enter(LockObj);
            try
            {
                connect.Close();
                connect.Dispose();
            }
            finally
            {
                Monitor.Exit(LockObj);
            }
        }

19 View Source File : ObjectStoreDaemon.cs
License : MIT License
Project Creator : azist

public void visit(bool stopping)
    {
      var now = App.LocalizedTime;
      for (var i = 0; i < m_BucketCount; i++)
      {
        var bucket = m_Buckets[i];
        if (stopping || bucket.LastAcquire.AddMilliseconds(MUST_ACQUIRE_INTERVAL_MS) < now)
          lock (bucket) write(bucket);
        else
        {
          if (Monitor.TryEnter(bucket))
          {
            try
            {
              write(bucket);
            }
            finally
            {
              Monitor.Exit(bucket);
            }
          }
        }
      }//for
    }

19 View Source File : RedisProxy.cs
License : Mozilla Public License 2.0
Project Creator : agebullhu

public void Dispose()
        {
            if (_client == null)
                return;
            Monitor.Enter(LockObj);
            try
            {
                //int dbid = (_db << 16);
                //Used[dbid].Remove(_client);
                _client.ResetSendBuffer();
                //if (_client.HadExceptions || Idle[dbid].Count > PoolSize)
                {
                    _client.Quit();
                    _client.Dispose();
                }
                //else
                //{
                //    Idle[dbid].Add(_client);
                //}
            }
            finally
            {
                Monitor.Exit(LockObj);
            }
        }

19 View Source File : DownloaderViewModel.cs
License : GNU General Public License v3.0
Project Creator : antikmozib

internal void Download_Stopped(object sender, EventArgs e)
        {
            if (this.DownloadingCount == 0)
            {
                this.Status = "Ready";
                RaisePropertyChanged(nameof(this.Status));

                if (this.QueuedCount == 0)
                {
                    this.QueueProcessor.Stop();
                }
            }

            RefreshCollection();

            Monitor.Enter(_lockBytesTransferredOverLifetime);
            try
            {
                Settings.Default.BytesTransferredOverLifetime +=
                    (ulong)(sender as DownloaderObjectModel).BytesDownloadedThisSession;
            }
            finally
            {
                Monitor.Exit(_lockBytesTransferredOverLifetime);
            }
        }

19 View Source File : TimedBlockingExecutor.cs
License : Apache License 2.0
Project Creator : akarnokd

internal void Run()
        {
            Thread.CurrentThread.IsBackground = true;
            Thread.CurrentThread.Name = name;
            var q = queue;
            for (;;)
            {
                if (Volatile.Read(ref shutdown))
                {
                    lock (q)
                    {
                        q.Clear();
                    }
                    break;
                }
                else
                {
                    long now = SchedulerHelper.NowUTC();
                    TimedTask tt = null;
                    int next = 0;
                    lock (q)
                    {
                        tt = q.FirstOrDefault();
                        if (tt != null)
                        {
                            if (tt.due <= now)
                            {
                                q.Remove(tt);
                            }
                            else
                            if (Volatile.Read(ref tt.action) == null)
                            {
                                q.Remove(tt);
                                continue;
                            }
                            else
                            {
                                next = (int)Math.Max(0, tt.due - now);
                                tt = null;
                            }
                        }
                        else
                        {
                            next = int.MaxValue;
                        }
                    }

                    if (tt != null)
                    {
                        if (Volatile.Read(ref shutdown))
                        {
                            lock (q)
                            {
                                q.Clear();
                            }
                            return;
                        }
                        var a = Volatile.Read(ref tt.action);
                        try
                        {
                            a?.Invoke();
                        }
                        catch
                        {
                            // TODO what should happen here?
                        }
                    }
                    else
                    {
                        if (Volatile.Read(ref shutdown))
                        {
                            lock (q)
                            {
                                q.Clear();
                            }
                            return;
                        }
                        if (Monitor.TryEnter(this))
                        {
                            Monitor.Wait(this, next);
                            Monitor.Exit(this);
                        }
                    }
                }
            }
        }

19 View Source File : OnceScope.cs
License : Mozilla Public License 2.0
Project Creator : agebullhu

protected override void OnDispose()
        {
            Monitor.Exit(_lockObj);
            _closeAction?.Invoke();
        }

19 View Source File : Channel.cs
License : Apache License 2.0
Project Creator : apache

public void Disable()
        {
            Monitor.Enter(_lock);
            _canSend = false;
            Monitor.Exit(_lock);
        }

19 View Source File : NamedLock.cs
License : MIT License
Project Creator : Adoxio

public IDisposable Lock(string name, int millisecondsTimeout)
		{
			Monitor.Enter(_locks);

			ReferenceCount obj;

			_locks.TryGetValue(name, out obj);

			if (obj == null)
			{
				obj = new ReferenceCount();

				Monitor.Enter(obj);

				_locks.Add(name, obj);

				Monitor.Exit(_locks);
			}
			else
			{
				obj.AddRef();

				Monitor.Exit(_locks);

				if (!Monitor.TryEnter(obj, millisecondsTimeout))
				{
					throw new TimeoutException(string.Format("A timeout occurred while waiting on the named lock {0}.", name));
				}
			}

			return new NamedLockHandle(this, name);
		}

19 View Source File : Configuration.cs
License : MIT License
Project Creator : Ashesh3

public void ShowWindow()
        {
            ConfigMail.Load();
            ConfigCaptcha.Load();

            BsMail.DataSource = ConfigMail.Running;
            BsCaptcha.DataSource = ConfigCaptcha.Running;

            Monitor.Enter(Misc.CaptchaConfigSync);
            Monitor.Enter(Misc.MailBoxConfigSync);
            var dialogResult = this.ShowDialog();
            Monitor.Exit(Misc.CaptchaConfigSync);
            Monitor.Exit(Misc.MailBoxConfigSync);

            if (dialogResult == DialogResult.OK)
            {
                ConfigMail.Save();
                ConfigCaptcha.Save();
            }
        }

19 View Source File : TimedBlockingExecutor.cs
License : Apache License 2.0
Project Creator : akarnokd

bool Offer(TimedTask tt)
        {
            lock (queue)
            {
                queue.Add(tt);
            }
            if (Volatile.Read(ref shutdown))
            {
                lock (queue)
                {
                    queue.Clear();
                }
                return false;
            }
            else
            {
                Monitor.Enter(this);
                Monitor.Pulse(this);
                Monitor.Exit(this);
            }
            return true;
        }

19 View Source File : Batch.cs
License : Apache License 2.0
Project Creator : awslabs

public void Stop()
        {
            //If already locked, probably will be flashed by other calls so don't wait indefinitely
            if (Monitor.TryEnter(_lockObject, 1000))
            {
                try
                {
                    Flush(FlushReason.Stop);
                }
                finally
                {
                    Monitor.Exit(_lockObject);
                }
            }
        }

19 View Source File : PXColorizerTaggerProvider.cs
License : GNU General Public License v3.0
Project Creator : Acumatica

private static void IncreaseCommentFormatTypesPrioirity(IClreplacedificationTypeRegistryService registry, IClreplacedificationFormatMapService formatMapService,
                                                               IClreplacedificationType highestPriorityType)
        {
            bool lockTaken = false;
            Monitor.TryEnter(_syncRoot, ref lockTaken);

            if (lockTaken)
            {
                try
                {
                    if (!_isPriorityIncreased)
                    {
                        _isPriorityIncreased = true;
                        IClreplacedificationFormatMap formatMap = formatMapService.GetClreplacedificationFormatMap(category: TextCategory);
                        IncreaseServiceFormatPriority(formatMap, registry, PredefinedClreplacedificationTypeNames.ExcludedCode, highestPriorityType);
                        IncreaseServiceFormatPriority(formatMap, registry, PredefinedClreplacedificationTypeNames.Comment, highestPriorityType);
                    }
                }
                finally
                {
                    Monitor.Exit(_syncRoot);
                }
            }
        }

19 View Source File : CappedSet.cs
License : MIT License
Project Creator : azist

private void visitCore()
    {
      var now = App.TimeSource.UTCNow;
      var toDelete = new HashSet<T>(m_Comparer);


      var ttlSec =  TimeLimitSec;
      var maxCount = SizeLimit;

      var overage = 0;
      if (maxCount>0)
        overage = m_Data.Sum( d => d.m_ApproximateCount ) - maxCount;

      var overagePerBucket = overage / m_Data.Length; //equal distribution is replacedumed per getBucket()

      for(var i=0; i<m_Data.Length; i++)
      {
        var dict = m_Data[i];
        var mustLock = (now - dict.m_LastLock).TotalSeconds > MUST_LOCK_BUCKET_SEC;

        if (!mustLock)
        {
          if (!Monitor.TryEnter(dict)) continue;
        }
        else Monitor.Enter(dict);
        try
        {
          dict.m_LastLock = now;//lock taken now

          toDelete.Clear();

          if (ttlSec>0) //impose time limit
            dict.Where(kvp => ((now - kvp.Value).TotalSeconds > ttlSec))
                .ForEach( kvp => toDelete.Add(kvp.Key));

          //impose count limit
          if (overagePerBucket > toDelete.Count)
          {
            var timeSorted = dict.OrderBy(kvp => kvp.Value);//ascending = older first
            foreach(var item in timeSorted)
             if (overagePerBucket>toDelete.Count)
              toDelete.Add( item.Key );
             else
              break;
          }

          toDelete.ForEach( k => dict.Remove(k) );
          dict.m_ApproximateCount = dict.Count;
        }
        finally
        {
          Monitor.Exit(dict);
        }
      }
    }

19 View Source File : BlockingSubscriber.cs
License : Apache License 2.0
Project Creator : akarnokd

public void Run()
        {
            var a = actual;
            var q = queue;
            long e = 0L;
            int consumed = 0;
            int lim = limit;
            for (;;)
            {
                if (SubscriptionHelper.IsCancelled(ref upstream))
                {
                    q.Clear();
                    return;
                }
                if (Volatile.Read(ref wip) == 0)
                {
                    Monitor.Enter(this);
                    try
                    {
                        while (Volatile.Read(ref wip) == 0 && SubscriptionHelper.IsCancelled(ref upstream))
                        {
                            Monitor.Wait(this);
                        }
                    }
                    finally
                    {
                        Monitor.Exit(this);
                    }
                }
                if (SubscriptionHelper.IsCancelled(ref upstream))
                {
                    q.Clear();
                    return;
                }

                bool d = Volatile.Read(ref done);
                bool empty = q.IsEmpty();

                if (d && empty)
                {
                    var ex = error;
                    if (ex != null)
                    {
                        a.OnError(ex);
                    }
                    else
                    {
                        a.OnComplete();
                    }
                    return;
                }

                if (!empty)
                {
                    if (e != Volatile.Read(ref requested))
                    {
                        q.Poll(out T v);

                        a.OnNext(v);

                        e++;
                        if (++consumed == lim)
                        {
                            consumed = 0;
                            upstream.Request(lim);
                        }    
                    }
                }
                Interlocked.Decrement(ref wip);
            }
        }

19 View Source File : BlockingQueueConsumer.cs
License : Apache License 2.0
Project Creator : akarnokd

internal bool Offer(Action task)
        {
            if (Volatile.Read(ref shutdown) == 0)
            {
                queue.Offer(task);
                if (Interlocked.Increment(ref wip) == 1)
                {
                    Monitor.Enter(this);
                    try
                    {
                        Monitor.Pulse(this);
                    }
                    finally
                    {
                        Monitor.Exit(this);
                    }
                }
                return true;
            }
            return false;
        }

19 View Source File : VideoSource.cs
License : MIT License
Project Creator : adamfisher

protected void OnLoadingStarted()
        {
            var obj = _syncHandle;
            var lockTaken = false;

            try
            {
                Monitor.Enter(obj, ref lockTaken);
                CancellationTokenSource = new CancellationTokenSource();
            }
            finally
            {
                if (lockTaken)
                    Monitor.Exit(obj);
            }
        }

19 View Source File : TimedBlockingExecutor.cs
License : Apache License 2.0
Project Creator : akarnokd

public void Dispose()
        {
            if (!Volatile.Read(ref shutdown))
            {
                Volatile.Write(ref shutdown, true);
                Monitor.Enter(this);
                Monitor.Pulse(this);
                Monitor.Exit(this);
            }
        }

19 View Source File : MutexScope.cs
License : Mozilla Public License 2.0
Project Creator : agebullhu

protected override void OnDispose()
        {
            Monitor.Exit(_lockObject);
        }

19 View Source File : DownloaderViewModel.cs
License : GNU General Public License v3.0
Project Creator : antikmozib

internal void Add(object obj)
        {
            if (_ctsUpdatingList != null)
            {
                ShowBusyMessage();
                return;
            }
            Monitor.Enter(_lockDownloadItemsList);
            try
            {
                var win = new AddDownloadWindow();
                var vm = new AddDownloadViewModel(AddItemsAsync, win.Preview, _displayMessage);
                win.DataContext = vm;
                win.Owner = obj as Window;
                win.ShowDialog();
            }
            finally
            {
                Monitor.Exit(_lockDownloadItemsList);
            }
        }

19 View Source File : MonoProtection.cs
License : Apache License 2.0
Project Creator : allenai

public void Dispose()
        {
            if (this.lockObject is object)
            {
                Monitor.Exit(this.lockObject);
            }
        }

19 View Source File : WSSocket.cs
License : Mozilla Public License 2.0
Project Creator : agebullhu

public void Dispose()
        {
            if (IsDisposed)
                return;
            IsDisposed = true;
            ShimHandler.Close();
            Monitor.Enter(ShimHandler);
            Monitor.Exit(ShimHandler);
            _actor.Dispose();
            _messagesPipe.Options.Linger = TimeSpan.Zero;
            _messagesPipe.Dispose();
        }

19 View Source File : DownloaderViewModel.cs
License : GNU General Public License v3.0
Project Creator : antikmozib

private void AddObjects(params DownloaderObjectModel[] objects)
        {
            Monitor.Enter(_lockDownloadItemsList);
            int total = objects.Count();
            try
            {
                Application.Current.Dispatcher.Invoke(() =>
                {
                    for (int i = 0; i < total; i++)
                    {
                        if (objects[i] == null) continue;

                        DownloadItemsList.Add(objects[i]);

                        if (objects[i].IsQueued)
                        {
                            this.QueueProcessor.Add(objects[i]);
                        }
                    }
                });
            }
            catch { }
            finally
            {
                Monitor.Exit(_lockDownloadItemsList);
            }
        }

19 View Source File : NamedLock.cs
License : MIT License
Project Creator : Adoxio

public void Unlock(string name)
		{
			lock (_locks)
			{
				ReferenceCount obj;

				_locks.TryGetValue(name, out obj);

				if (obj != null)
				{
					Monitor.Exit(obj);

					if (0 == obj.Release())
					{
						_locks.Remove(name);
					}
				}
			}
		}

19 View Source File : LocalDatabaseContext.cs
License : MIT License
Project Creator : AntonyCorbett

public void Dispose()
        {
            Db.Dispose();
            Monitor.Exit(Locker);
        }

19 View Source File : BaseShimHandler.cs
License : Mozilla Public License 2.0
Project Creator : agebullhu

public void Close()
        {
            if (!isRuning)
                return;
            isRuning = true;
            Stream.Unbind(Address);
            MessagesPipe.Disconnect($"inproc://wsrouter-{Id}");

            Poller.Dispose();
            Monitor.Enter(this);
            try
            {
                Stream.Dispose();
                MessagesPipe.Dispose();
            }
            finally
            {
                Monitor.Exit(this);
            }
        }

19 View Source File : Channel.cs
License : Apache License 2.0
Project Creator : apache

public IDisposable Enter()
        {
            Monitor.Enter(_lock);

            if (_canSend)
                return this;

            Monitor.Exit(_lock);
            throw new OperationCanceledException();
        }

19 View Source File : GameFix.cs
License : Apache License 2.0
Project Creator : AantCoder

[HarmonyPostfix]
            public static void Postfix()
            {
                Monitor.Exit(ThingOwnerUtility_GetAllThingsRecursively_Patch.SuncObj);
            }

19 View Source File : ParallelDeflateOutputStream.cs
License : Apache License 2.0
Project Creator : Appdynamics

private void EmitPendingBuffers(bool doAll, bool mustWait)
        {
            // When combining parallel deflation with a ZipSegmentedStream, it's
            // possible for the ZSS to throw from within this method.  In that
            // case, Close/Dispose will be called on this stream, if this stream
            // is employed within a using or try/finally pair as required. But
            // this stream is unaware of the pending exception, so the Close()
            // method invokes this method AGAIN.  This can lead to a deadlock.
            // Therefore, failfast if re-entering.

            if (emitting) return;
            emitting = true;
            if (doAll || mustWait)
                _newlyCompressedBlob.WaitOne();

            do
            {
                int firstSkip = -1;
                int millisecondsToWait = doAll ? 200 : (mustWait ? -1 : 0);
                int nextToWrite = -1;

                do
                {
                    if (Monitor.TryEnter(_toWrite, millisecondsToWait))
                    {
                        nextToWrite = -1;
                        try
                        {
                            if (_toWrite.Count > 0)
                                nextToWrite = _toWrite.Dequeue();
                        }
                        finally
                        {
                            Monitor.Exit(_toWrite);
                        }

                        if (nextToWrite >= 0)
                        {
                            WorkItem workitem = _pool[nextToWrite];
                            if (workitem.ordinal != _lastWritten + 1)
                            {
                                // out of order. requeue and try again.
                                TraceOutput(TraceBits.EmitSkip,
                                            "Emit     skip     wi({0}) ord({1}) lw({2}) fs({3})",
                                            workitem.index,
                                            workitem.ordinal,
                                            _lastWritten,
                                            firstSkip);

                                lock(_toWrite)
                                {
                                    _toWrite.Enqueue(nextToWrite);
                                }

                                if (firstSkip == nextToWrite)
                                {
                                    // We went around the list once.
                                    // None of the items in the list is the one we want.
                                    // Now wait for a compressor to signal again.
                                    _newlyCompressedBlob.WaitOne();
                                    firstSkip = -1;
                                }
                                else if (firstSkip == -1)
                                    firstSkip = nextToWrite;

                                continue;
                            }

                            firstSkip = -1;

                            TraceOutput(TraceBits.EmitBegin,
                                        "Emit     begin    wi({0}) ord({1})              cba({2})",
                                        workitem.index,
                                        workitem.ordinal,
                                        workitem.compressedBytesAvailable);

                            _outStream.Write(workitem.compressed, 0, workitem.compressedBytesAvailable);
                            _runningCrc.Combine(workitem.crc, workitem.inputBytesAvailable);
                            _totalBytesProcessed += workitem.inputBytesAvailable;
                            workitem.inputBytesAvailable = 0;

                            TraceOutput(TraceBits.EmitDone,
                                        "Emit     done     wi({0}) ord({1})              cba({2}) mtw({3})",
                                        workitem.index,
                                        workitem.ordinal,
                                        workitem.compressedBytesAvailable,
                                        millisecondsToWait);

                            _lastWritten = workitem.ordinal;
                            _toFill.Enqueue(workitem.index);

                            // don't wait next time through
                            if (millisecondsToWait == -1) millisecondsToWait = 0;
                        }
                    }
                    else
                        nextToWrite = -1;

                } while (nextToWrite >= 0);

            //} while (doAll && (_lastWritten != _latestCompressed));
            } while (doAll && (_lastWritten != _latestCompressed || _lastWritten != _lastFilled));

            emitting = false;
        }

19 View Source File : KeyRingProvider.cs
License : Apache License 2.0
Project Creator : Aguafrommars

internal IKeyRing GetCurrentKeyRingCore(DateTime utcNow, bool forceRefresh = false)
        {
            Debug.replacedert(utcNow.Kind == DateTimeKind.Utc);

            // Can we return the cached keyring to the caller?
            CacheableKeyRing existingCacheableKeyRing = null;
            if (!forceRefresh)
            {
                existingCacheableKeyRing = Volatile.Read(ref _cacheableKeyRing);
                if (CacheableKeyRing.IsValid(existingCacheableKeyRing, utcNow))
                {
                    return existingCacheableKeyRing.KeyRing;
                }
            }

            // The cached keyring hasn't been created or must be refreshed. We'll allow one thread to
            // update the keyring, and all other threads will continue to use the existing cached
            // keyring while the first thread performs the update. There is an exception: if there
            // is no usable existing cached keyring, all callers must block until the keyring exists.
            var acquiredLock = false;
            try
            {
                Monitor.TryEnter(_cacheableKeyRingLockObj, (existingCacheableKeyRing != null) ? 0 : Timeout.Infinite, ref acquiredLock);
                if (acquiredLock)
                {
                    return GetCurrentKeyRingSync(utcNow, forceRefresh, ref existingCacheableKeyRing);
                }
                else
                {
                    // We didn't acquire the critical section. This should only occur if we preplaceded
                    // zero for the Monitor.TryEnter timeout, which implies that we had an existing
                    // (but outdated) keyring that we can use as a fallback.
                    Debug.replacedert(existingCacheableKeyRing != null);
#pragma warning disable S2259 // Null pointers should not be dereferenced
                    return existingCacheableKeyRing.KeyRing;
#pragma warning restore S2259 // Null pointers should not be dereferenced
                }
            }
            finally
            {
                if (acquiredLock)
                {
                    Monitor.Exit(_cacheableKeyRingLockObj);
                }
            }
        }

19 View Source File : DefaultHttpClientFactory.cs
License : Apache License 2.0
Project Creator : aspnet

internal void CleanupTimer_Tick()
        {
            // Stop any pending timers, we'll restart the timer if there's anything left to process after cleanup.
            //
            // With the scheme we're using it's possible we could end up with some redundant cleanup operations.
            // This is expected and fine.
            // 
            // An alternative would be to take a lock during the whole cleanup process. This isn't ideal because it
            // would result in threads executing ExpiryTimer_Tick as they would need to block on cleanup to figure out
            // whether we need to start the timer.
            StopCleanupTimer();

            if (!Monitor.TryEnter(_cleanupActiveLock))
            {
                // We don't want to run a concurrent cleanup cycle. This can happen if the cleanup cycle takes
                // a long time for some reason. Since we're running user code inside Dispose, it's definitely
                // possible.
                //
                // If we end up in that position, just make sure the timer gets started again. It should be cheap
                // to run a 'no-op' cleanup.
                StartCleanupTimer();
                return;
            }

            try
            {
                var initialCount = _expiredHandlers.Count;
                Log.CleanupCycleStart(_logger, initialCount);

                var stopwatch = ValueStopwatch.StartNew();

                var disposedCount = 0;
                for (var i = 0; i < initialCount; i++)
                {
                    // Since we're the only one removing from _expired, TryDequeue must always succeed.
                    _expiredHandlers.TryDequeue(out var entry);
                    Debug.replacedert(entry != null, "Entry was null, we should always get an entry back from TryDequeue");

                    if (entry.CanDispose)
                    {
                        try
                        {
                            entry.InnerHandler.Dispose();
                            entry.Scope?.Dispose();
                            disposedCount++;
                        }
                        catch (Exception ex)
                        {
                            Log.CleanupItemFailed(_logger, entry.Name, ex);
                        }
                    }
                    else
                    {
                        // If the entry is still live, put it back in the queue so we can process it 
                        // during the next cleanup cycle.
                        _expiredHandlers.Enqueue(entry);
                    }
                }

                Log.CleanupCycleEnd(_logger, stopwatch.GetElapsedTime(), disposedCount, _expiredHandlers.Count);
            }
            finally
            {
                Monitor.Exit(_cleanupActiveLock);
            }

            // We didn't totally empty the cleanup queue, try again later.
            if (_expiredHandlers.Count > 0)
            {
                StartCleanupTimer();
            }
        }

19 View Source File : RedisProxy.Core.cs
License : Mozilla Public License 2.0
Project Creator : agebullhu

private IDatabase CreateClient(int db)
        {
            Monitor.Enter(LockObj);
            try
            {
                if (connect == null)
                {
                    connect = ConnectionMultiplexer.Connect($"{Address}:{Port}");
                }
                if (_client != null && _db == db)
                    return _client;
                return connect.GetDatabase(db);
            }
            finally
            {
                Monitor.Exit(LockObj);
            }
        }

19 View Source File : RequestLimitControl.cs
License : GNU General Public License v3.0
Project Creator : atomex-me

public async Task Wait(CancellationToken cancellationToken)
        {
            var isCompleted = false;

            while (!isCompleted)
            {
                if (cancellationToken.IsCancellationRequested)
                    cancellationToken.ThrowIfCancellationRequested();

                Monitor.Enter(_sync);

                var timeStampMs = DateTime.Now.ToUnixTimeMs();
                var differenceMs = timeStampMs - _lastRequestTimeStampMs;

                if (differenceMs < _minDelayBetweenRequestMs)
                {
                    Monitor.Exit(_sync);

                    await Task.Delay((int)(_minDelayBetweenRequestMs - differenceMs), cancellationToken)
                        .ConfigureAwait(false);
                }
                else
                {
                    _lastRequestTimeStampMs = timeStampMs;
                    Monitor.Exit(_sync);

                    isCompleted = true;
                }
            }
        }

19 View Source File : BlockingLambdaSubscriber.cs
License : Apache License 2.0
Project Creator : akarnokd

public void Run()
        {
            for (;;)
            {
                if (SubscriptionHelper.IsCancelled(ref upstream))
                {
                    return;
                }
                if (Volatile.Read(ref wip) == 0)
                {
                    Monitor.Enter(this);
                    try
                    {
                        for (;;)
                        {
                            if (SubscriptionHelper.IsCancelled(ref upstream))
                            {
                                return;
                            }

                            if (Volatile.Read(ref wip) != 0)
                            {
                                break;
                            }
                            Monitor.Wait(this);
                        }
                    }
                    finally
                    {
                        Monitor.Exit(this);
                    }
                }
                if (queue.Poll(out T current))
                {
                    int c = consumed + 1;
                    if (c == limit)
                    {
                        consumed = 0;
                        upstream.Request(c);
                    }
                    else
                    {
                        consumed = c;
                    }
                    onNext(current);
                    Interlocked.Decrement(ref wip);
                    continue;
                }
                var ex = error;
                if (ex != null)
                {
                    onError(ex);
                }
                else
                {
                    onComplete();
                }
                return;
            }
        }

19 View Source File : Batch.cs
License : Apache License 2.0
Project Creator : awslabs

private void OnTimer(object state)
        {
            //If already locked, simply skip
            if (Monitor.TryEnter(_lockObject))
            {
                try
                {
                    Flush(FlushReason.Timer);
                }
                finally
                {
                    Monitor.Exit(_lockObject);
                }
            }
        }

19 View Source File : CallBinder.cs
License : MIT License
Project Creator : 71

public void Dispose()
            {
                inContext = false;

                invocationSymbol = null;
                statementSymbol = null;

                expressionSyntax = null;
                statementSyntax = null;

                callerInfo = null;
                callerSymbol = null;

                methodInfo = null;
                methodSymbol = null;

                Monitor.Exit(syncObject);
            }

19 View Source File : Node.cs
License : GNU Lesser General Public License v2.1
Project Creator : axiom3d

protected internal virtual void Update(bool updateChildren, bool hasParentChanged)
        {
            if (this.parent == null)
            {
                Monitor.Enter(_queuedForUpdate);
            }

            this.isParentNotified = false;

            // skip update if not needed
            if (!updateChildren && !this.needParentUpdate && !this.needChildUpdate && !hasParentChanged)
            {
                return;
            }

            // see if need to process everyone
            if (this.needParentUpdate || hasParentChanged)
            {
                // update transforms from parent
                UpdateFromParent();

                if (NodeUpdated != null)
                {
                    NodeUpdated(this);
                }
            }

            // see if we need to process all
            if (this.needChildUpdate || hasParentChanged)
            {
                // update all children
                foreach (var child in this.childNodes.Values)
                {
                    child.Update(true, true);
                }

                this.childrenToUpdate.Clear();
            }
            else
            {
                // just update selected children
                foreach (var child in this.childrenToUpdate.Values)
                {
                    child.Update(true, false);
                }

                // clear the list
                this.childrenToUpdate.Clear();
            }

            // reset the flag
            this.needChildUpdate = false;

            if (this.parent == null)
            {
                Monitor.Exit(_queuedForUpdate);
            }
        }

19 View Source File : BlockingEnumeratorSubscriber.cs
License : Apache License 2.0
Project Creator : akarnokd

public bool MoveNext()
        {
            if (SubscriptionHelper.IsCancelled(ref upstream))
            {
                return false;
            }
            if (Volatile.Read(ref wip) == 0)
            {
                Monitor.Enter(this);
                try
                {
                    for (;;)
                    {
                        if (SubscriptionHelper.IsCancelled(ref upstream))
                        {
                            return false;
                        }

                        if (Volatile.Read(ref wip) != 0)
                        {
                            break;
                        }
                        Monitor.Wait(this);
                    }
                }
                finally
                {
                    Monitor.Exit(this);
                }
            }
            if (queue.Poll(out current))
            {
                int c = consumed + 1;
                if (c == limit)
                {
                    consumed = 0;
                    upstream.Request(c);
                }
                else
                {
                    consumed = c;
                }
                Interlocked.Decrement(ref wip);
                return true;
            }
            var ex = error;
            if (ex != null)
            {
                throw ex;
            }
            return false;
        }

19 View Source File : RedisProxy.cs
License : Mozilla Public License 2.0
Project Creator : agebullhu

private RedisClient CreateClient(long db)
        {
            Monitor.Enter(LockObj);
            try
            {
                //var dbid = (this.db << 16);
                return new RedisClient(Address, Port, PreplacedWord, db)
                {
                    RetryCount = 50,
                    RetryTimeout = 5000
                };
                /*List<RedisClient> used;
                    if (!Used.ContainsKey(dbid))
                    {
                        Used.Add(dbid, used = new List<RedisClient>());
                        Idle.Add(dbid, new List<RedisClient>());

                        _client = new RedisClient(Address, Port, null, db)
                        {
                            RetryCount = 50,
                            RetryTimeout = 5000
                        };
                        used.Add(_client);
                        return Client;
                    }
                    used = Used[dbid];
                    List<RedisClient> idle = Idle[dbid];
                    while (idle.Count > 0 && idle[0] == null)
                    {
                        idle.RemoveAt(0);
                    }
                    if (idle.Count == 0)
                    {
                        _client = new RedisClient(Address, Port, null, db)
                        {
                            RetryCount = 50,
                            RetryTimeout = 5000
                        };
                        used.Add(_client);
                        return _client;
                    }
                    _client = idle[0];
                    idle.RemoveAt(0);
#if DEBUG
                    _client.Ping();
#endif
                    used.Add(_client);
                    return _client;*/
            }
            finally
            {
                Monitor.Exit(LockObj);
            }
        }

19 View Source File : Lock.cs
License : MIT License
Project Creator : 0x0ade

protected virtual void Dispose(bool disposing) {
        if (disposing)
            Monitor.Exit(m_pObject);
    }

19 View Source File : GameFix.cs
License : Apache License 2.0
Project Creator : AantCoder

[HarmonyPostfix]
            public static void Postfix()
            {
                Monitor.Exit(SuncObj);
            }

19 View Source File : VideoSource.cs
License : MIT License
Project Creator : adamfisher

protected void OnLoadingCompleted(bool cancelled)
        {
            if (!IsLoading || this._completionSource == null)
                return;

            var completionSource = Interlocked.Exchange(ref this._completionSource, null);
            completionSource?.SetResult(cancelled);

            var obj = _syncHandle;
            var lockTaken = false;

            try
            {
                Monitor.Enter(obj, ref lockTaken);
                CancellationTokenSource = null;
            }
            finally
            {
                if (lockTaken)
                    Monitor.Exit(obj);
            }
        }

19 View Source File : StackExchangeRedis.cs
License : Mozilla Public License 2.0
Project Creator : agebullhu

private IDatabase CreateClient(int db)
        {
            Monitor.Enter(LockObj);
            try
            {
                if (_client == null || db != _client.Database)
                    _client = _connect.GetDatabase(db);
                _db = _client.Database;
                return _client;
            }
            catch (Exception ex)
            {
                LogRecorderX.Exception(ex, ConnectString);
                throw;
            }
            finally
            {
                Monitor.Exit(LockObj);
            }
        }

19 View Source File : SQLiteAsync.cs
License : GNU General Public License v3.0
Project Creator : andysal

public void Dispose ()
			{
				Monitor.Exit (_lockPoint);
			}

See More Examples