Example #1
0
        public void TryAddCount_Invalid()
        {
            using (var ev = new CountdownEvent(1))
            {
                try
                {
                    ev.TryAddCount(0);
                    Assert.Fail("#1");
                }
                catch (ArgumentOutOfRangeException ex)
                {
                    Theraot.No.Op(ex);
                }

                try
                {
                    ev.TryAddCount(-1);
                    Assert.Fail("#2");
                }
                catch (ArgumentOutOfRangeException ex)
                {
                    Theraot.No.Op(ex);
                }
            }
        }
        public void TryAddCountTestCase()
        {
            var evt = new CountdownEvent(5);

            Assert.IsTrue(evt.TryAddCount(2), "#1");
            evt.Signal(7);
            Assert.IsFalse(evt.TryAddCount(), "#2");
        }
Example #3
0
 public IDisposable DeferDisposal()
 {
     if (!_countdown.TryAddCount())
     {
         throw new ObjectDisposedException(GetType().Name);
     }
     return(Create(() => _countdown?.Signal()));
 }
Example #4
0
 private void MoveEnvironmentToDisposeState()
 {
     _envDispose.Signal(); // release the owner count
     if (_envDispose.Wait(Options.DisposeWaitTime) == false)
     {
         if (_envDispose.TryAddCount(1))
         // try restore the previous signal, if it failed, the _envDispose is signaled
         {
             var activeTxs = ActiveTransactions.AllTransactions;
             ThrowInvalidDisposeDuringActiveTransactions(activeTxs);
         }
     }
 }
Example #5
0
        public void SendPushMessage(PushMessage message, bool isWriteToBuffer, out bool isSended)
        {
            isSended = IsSending(message);
            if (!isSended)
            {
                if (isWriteToBuffer)
                {
                    _sendMessagePool.Write(message);
                }
                else
                {
                    while (m_sendMessageCDE.CurrentCount > 1000)
                    {
                        Process.Info(message.PushId, "消息通知单条发送接口", "SendPushMessage", "", "m_sendMessageCDE:" + m_sendMessageCDE.CurrentCount.ToString(), "阻塞");
                        Thread.Sleep(100);
                    }

                    ThreadPool.QueueUserWorkItem((o) =>
                    {
                        try
                        {
                            Process.Info(message.PushId, "消息通知单条发送接口", "SendPushMessage", "", string.Format("批次【{0}】,数量【{1}】", ++callCount, 1), "");
                            m_sendMessageCDE.TryAddCount(1);
                            m_client.Receive(message);
                            if (m_sendMessageCDE.CurrentCount > 0)
                            {
                                m_sendMessageCDE.TryAddCount(-1);
                            }
                            Process.Info(message.PushId, "消息通知单条发送接口_返回", "SendPushMessage", "", string.Format("批次【{0}】,数量【{1}】", ++callCount, 1), "");
                        }
                        catch (Exception ex)
                        {
                            if (m_sendMessageCDE.CurrentCount > 0)
                            {
                                m_sendMessageCDE.TryAddCount(-1);
                            }
                            if (m_client.State == CommunicationState.Closed ||
                                m_client.State == CommunicationState.Faulted)
                            {
                                m_client = new ServiceAgent.SenderSendServiceSOA.SendServiceClient();
                            }
                            //如果推送异常,去掉标示的推送缓存
                            string cacheKey = string.Format(CacheKeys.PushMessageToSender_Arg2, message.PushId, message.PushCount);
                            DistributedCache.Delete(cacheKey);
                            Process.Error(message.PushId, "消息通知单条发送接口", "SendPushMessage", "", "异步发送推送消息到消息通知接口出现异常:" + ex.GetString(), "Error");
                        }
                    });
                }
            }
        }
Example #6
0
        /// <summary>
        /// Enqueue the command to be eventually executed. If the command implements
        ///  IDisposable, the command will be disposed after it is run and a tx is committed.
        /// </summary>
        public async ValueTask <bool> Enqueue(MergedTransactionCommand cmd)
        {
            _edi?.Throw();

            _operations.Enqueue(cmd);
            _waitHandle.Set();

            if (_concurrentOperations.TryAddCount() == false)
            {
                ThrowTxMergerWasDisposed();
            }

            try
            {
                await cmd.TaskCompletionSource.Task;
            }
            finally
            {
                try
                {
                    _concurrentOperations.Signal(); // done with this
                }
                catch (InvalidOperationException)
                {
                    // Expected: "Invalid attempt made to decrement the event's count below zero."
                }
            }

            return(true);
        }
Example #7
0
        public void CurrentCountTestCase()
        {
            Assert.AreEqual(5, evt.CurrentCount, "#1");

            evt.AddCount();
            Assert.AreEqual(6, evt.CurrentCount, "#2");

            evt.TryAddCount(2);
            Assert.AreEqual(8, evt.CurrentCount, "#3");

            evt.Signal(4);
            Assert.AreEqual(4, evt.CurrentCount, "#4");

            evt.Reset();
            Assert.AreEqual(5, evt.CurrentCount, "#5");
        }
        public void TryAddCount_Invalid()
        {
            var ev = new CountdownEvent(1);

            try {
                ev.TryAddCount(0);
                Assert.Fail("#1");
            } catch (ArgumentOutOfRangeException) {
            }

            try {
                ev.TryAddCount(-1);
                Assert.Fail("#2");
            } catch (ArgumentOutOfRangeException) {
            }
        }
Example #9
0
        private async Task ProcessNotificationAsync(INotification notification)
        {
            try
            {
                if (m_processingCountdown.TryAddCount())
                {
                    await m_listener.On((dynamic)notification);
                }
                else
                {
                    var redeliveredNotification = notification.RedeliverTo(m_listener);

                    s_logger.Warning(
                        "Trying to redeliver notification (RedeliverNotificationId}, {NotificationType}) " +
                        "to consumer {ListenerType} because subscription is stopping. " +
                        "Source notification: {SourceNotificationId}.",
                        redeliveredNotification.NotificationId,
                        redeliveredNotification.NotificationType,
                        GetConsumerId(),
                        notification.NotificationId);

                    await m_notificationsChannel.SendAsync(redeliveredNotification);
                }
            }
            finally
            {
                if (!m_processingCountdown.IsSet)
                {
                    m_processingCountdown.Signal();
                }
            }
        }
 public static void ForceAddCount(this CountdownEvent cde, int signalCount = 1)
 {
     lock (cde)
     {
         if (!cde.TryAddCount(signalCount))
         {
             cde.Reset(signalCount);
         }
     }
 }
Example #11
0
        private static string RetrieveData()
        {
            if (!_readCount.TryAddCount())
            {
                _readCount.Reset(1);
            }

            Console.WriteLine("Thread {0} is reading data, read count is at {1}", Thread.CurrentThread.ManagedThreadId, _readCount.CurrentCount);
            string data = File.ReadAllText(_cachePath);

            _readCount.Signal();

            return(data);
        }
        public void TryAddCount_HasBeenSet()
        {
            var ev = new CountdownEvent(0);

            Assert.IsFalse(ev.TryAddCount(1), "#1");

            ev = new CountdownEvent(1);
            ev.Signal();
            Assert.IsFalse(ev.TryAddCount(1), "#2");

            ev = new CountdownEvent(2);
            ev.Signal(2);
            Assert.IsFalse(ev.TryAddCount(66), "#3");
        }
 public void HandItemsToThreadsLoop()
 {
     if (myDelegates.Count != 0 && myEvent.CurrentCount != Math.Min(myDelegates.Count, MaxThreads))
     {
         if (myEvent.IsSet)
         {
             myEvent = new CountdownEvent(Math.Min(myDelegates.Count, MaxThreads));
             LoadCurrentDelegates();
         }
         else if (myEvent.TryAddCount(Math.Min(myDelegates.Count, MaxThreads))) //will return false if is set
         {
             LoadCurrentDelegates();
         }
     }
 }
        private void SplitNode(TNode node, int depth, TState state)
        {
            if (_cancellationToken.IsCancellationRequested)
            {
                return;
            }

            TNode continuationNode = null;

            foreach (var child in node.Children)
            {
                if (child.TryLockNode() && _currentGenerationCounter.TryAddCount())
                {
                    if (continuationNode == null)
                    {
                        continuationNode = child;
                    }
                    else
                    {
                        // todo - rework closure
                        var stateCopy  = _stateTransitions.Copy(state);
                        var localState = _stateTransitions.GoDown(stateCopy, child);
                        ThreadPool.QueueUserWorkItem(
                            obj =>
                        {
                            child.UpdateAlfaBeta(node);
                            GoDown(child, localState, depth - 1, node);
                            _stateTransitions.DeallocateCopy(stateCopy);
                            try
                            {
                                _currentGenerationCounter.Signal();
                            }
                            catch (InvalidOperationException) { }
                        }
                            );
                    }
                }
            }

            if (continuationNode != null)
            {
                continuationNode.UpdateAlfaBeta(node);
                var localState = _stateTransitions.GoDown(state, continuationNode);
                GoDown(continuationNode, localState, depth - 1, continuationNode);
                _currentGenerationCounter.Signal();
            }
        }
        public void Dispose()
        {
            var ce = new CountdownEvent(1);

            ce.Dispose();
            Assert.AreEqual(1, ce.CurrentCount, "#0a");
            Assert.AreEqual(1, ce.InitialCount, "#0b");
            Assert.IsFalse(ce.IsSet, "#0c");

            try {
                ce.AddCount();
                Assert.Fail("#1");
            } catch (ObjectDisposedException) {
            }

            try {
                ce.Reset();
                Assert.Fail("#2");
            } catch (ObjectDisposedException) {
            }

            try {
                ce.Signal();
                Assert.Fail("#3");
            } catch (ObjectDisposedException) {
            }

            try {
                ce.TryAddCount();
                Assert.Fail("#4");
            } catch (ObjectDisposedException) {
            }

            try {
                ce.Wait(5);
                Assert.Fail("#4");
            } catch (ObjectDisposedException) {
            }

            try {
                var v = ce.WaitHandle;
                Assert.Fail("#5");
            } catch (ObjectDisposedException) {
            }
        }
Example #16
0
 public bool Invoke()
 {
     if (m_Pending.TryAddCount())
     {
         try
         {
             if (m_Callback != null)
             {
                 m_Callback();
             }
         }
         finally
         {
             m_Pending.Signal();
         }
         return(true);
     }
     return(false);
 }
Example #17
0
        public void CurrentCountTestCase()
        {
            using (var evt = new CountdownEvent(5))
            {
                Assert.AreEqual(5, evt.CurrentCount, "#1");

                evt.AddCount();
                Assert.AreEqual(6, evt.CurrentCount, "#2");

                evt.TryAddCount(2);
                Assert.AreEqual(8, evt.CurrentCount, "#3");

                evt.Signal(4);
                Assert.AreEqual(4, evt.CurrentCount, "#4");

                evt.Reset();
                Assert.AreEqual(5, evt.CurrentCount, "#5");
            }
        }
        private void AddSubscriber()
        {
            // when child subscribers attach they need to be synchronized to the master stream
            // this is allowed outside of "reset" event boundary.
            // the broadcaster will yield to any _waitingSubscribers before resuming work
            lock (_lock)
            {
                // need to do this under lock because we can't just increment if the lock is already set, and there's a
                // risk of collision of two threads resetting to 1 at the same time
                if (!_waitingSubscribers.TryAddCount())
                {
                    _waitingSubscribers.Reset(1);
                }
            }

            if (_subscribers == 0)
            {
                _masterSubscription = _masterObservable.Connect();
            }
            _subscribers++;
        }
        public Stream GetContentStream()
        {
            bool deletionLock = deletionCountdown.TryAddCount();

            if (!deletionLock)
            {
                throw new FileNotFoundException("The cached file has been deleted.");
            }
            if (!created)
            {
                lock (creationLock)
                {
                    if (!created)
                    {
                        var dynamicTemplateData = new DynamicTemplateData(templateData);
                        using (var document = template.CreateDocument())
                        {
                            using (var fileStream = File.Create(path))
                            {
                                using (var pdfWriter = PdfWriter.GetInstance(document, fileStream))
                                {
                                    document.Open();
                                    template.WriteDocument(document, dynamicTemplateData);
                                    document.Close();
                                }
                            }
                        }

                        this.CreationDate = File.GetCreationTimeUtc(path);
                        this.created      = true;
                    }
                }
            }

            return(File.OpenRead(path));
        }