コード例 #1
0
        /// <summary>
        /// Invoke the <seealso cref="IAgent.DoWork()"/> method and return the work count.
        ///
        /// If an error occurs then the <seealso cref="AtomicCounter.Increment"/> will be called on the errorCounter if not null
        /// and the <seealso cref="Exception"/> will be passed to the <seealso cref="ErrorHandler"/> method. If the error
        /// is an <seealso cref="AgentTerminationException"/> then <seealso cref="Dispose"/> will be called after the error handler.
        ///
        /// If not successfully started or after closed then this method will return without invoking the <seealso cref="Agent"/>.
        ///
        /// </summary>
        /// <returns> the work count for the <seealso cref="IAgent.DoWork"/> method. </returns>
        public int Invoke()
        {
            int workCount = 0;

            if (IsRunning)
            {
                try
                {
                    workCount = _agent.DoWork();
                }
                catch (ThreadInterruptedException)
                {
                    Dispose();
                    Thread.CurrentThread.Interrupt();
                }
                catch (AgentTerminationException ex)
                {
                    HandleError(ex);
                    Dispose();
                }
                catch (Exception exception)
                {
                    if (null != _errorCounter)
                    {
                        _errorCounter.Increment();
                    }

                    _errorHandler(exception);
                }
            }

            return(workCount);
        }
コード例 #2
0
        protected override void Decode(IChannelHandlerContext context, IByteBuffer input, List <object> output)
        {
            string msg = string.Empty;

            byte[] buffer = null;
            try
            {
                buffer = new byte[input.Capacity + 2];
                input.ReadBytes(buffer, 1, input.Capacity);
                buffer[0] = JT809Package.BEGINFLAG;
                buffer[input.Capacity + 1] = JT809Package.ENDFLAG;
                output.Add(JT809Serializer.Deserialize(buffer));
                MsgSuccessCounter.Increment();
                if (logger.IsEnabled(LogLevel.Debug))
                {
                    msg = ByteBufferUtil.HexDump(buffer);
                    logger.LogDebug("accept package <<<" + msg);
                    logger.LogDebug("accept package success count<<<" + MsgSuccessCounter.Count.ToString());
                }
            }
            catch (JT809Exception ex)
            {
                MsgFailCounter.Increment();
                logger.LogError("accept package fail count<<<" + MsgFailCounter.Count.ToString());
                logger.LogError(ex, $"{ex.ErrorCode.ToString()}accept msg<<<{msg}");
                return;
            }
            catch (Exception ex)
            {
                MsgFailCounter.Increment();
                logger.LogError("accept package fail count<<<" + MsgFailCounter.Count.ToString());
                logger.LogError(ex, "accept msg<<<" + msg);
                return;
            }
        }
コード例 #3
0
        /// <summary>
        /// Process a colKeys of specified items in a most optimal way according to
        /// the bundle settings.
        /// </summary>
        /// <param name="colKeys">
        /// The collection of keys to process.
        /// </param>
        /// <returns>
        /// An execution result according to the caller's contract.
        /// </returns>
        public IDictionary ProcessAll(ICollection colKeys)
        {
            AtomicCounter counter  = m_countThreads;
            int           cThreads = (int)counter.Increment();

            try
            {
                if (cThreads < ThreadThreshold)
                {
                    return(Bundling(colKeys));
                }

                Bundle bundle;
                bool   isBurst;
                while (true)
                {
                    bundle = (Bundle)getOpenBundle();
                    lock (bundle)
                    {
                        if (bundle.IsOpen())
                        {
                            bool isFirst = bundle.AddAll(colKeys);

                            isBurst = bundle.WaitForResults(isFirst);
                            break;
                        }
                    }
                }
                return(bundle.ProcessAll(isBurst, colKeys));
            }
            finally
            {
                counter.Decrement();
            }
        }
コード例 #4
0
        /// <summary>
        /// Process the specified key in a most optimal way according to the
        /// bundle settings.
        /// </summary>
        /// <param name="key">
        /// The key to process.
        /// </param>
        /// <returns>
        /// An execution result according to the caller's contract.
        /// </returns>
        public Object Process(Object key)
        {
            AtomicCounter counter  = m_countThreads;
            int           cThreads = (int)counter.Increment();

            try
            {
                if (cThreads < ThreadThreshold)
                {
                    return(Unbundling(key));
                }

                Bundle bundle;
                bool   isBurst;
                while (true)
                {
                    bundle = (Bundle)getOpenBundle();
                    lock (bundle)
                    {
                        if (bundle.IsOpen())
                        {
                            bool isFirst = bundle.Add(key);

                            isBurst = bundle.WaitForResults(isFirst);
                            break;
                        }
                    }
                }
                return(bundle.Process(isBurst, key));
            }
            finally
            {
                counter.Decrement();
            }
        }
コード例 #5
0
ファイル: AgentInvoker.cs プロジェクト: chrisejones/Aeron.NET
        public int Invoke()
        {
            int workCount = 0;

            if (!_closed)
            {
                try
                {
                    workCount = _agent.DoWork();
                }
                catch (ThreadInterruptedException)
                {
                }
                catch (Exception exception)
                {
                    if (null != _errorCounter)
                    {
                        _errorCounter.Increment();
                    }

                    _errorHandler(exception);
                }
            }

            return(workCount);
        }
コード例 #6
0
        public void AtomicCounter_ParallelCounter()
        {
            var k = 0;

            Parallel.For(0, 100, (i, loop) =>
            {
                Interlocked.Increment(ref k);

                var counter = new AtomicCounter();

                Assert.AreEqual(0, counter.Value);

                void Inc()
                {
                    counter.Increment();
                }

                void Dec()
                {
                    counter.Decrement();
                }

                Parallel.Invoke(Inc, Inc, Dec, Dec, Dec, Inc, Dec, Inc, Dec, Inc, Inc, Inc, Dec, Dec, Inc);

                Assert.AreEqual(1, counter.Value);
            });

            Assert.AreEqual(100, k);
        }
コード例 #7
0
        public void AtomicCounter__ParallelIncrement()
        {
            var k = 0;

            var global = new AtomicCounter();

            Parallel.For(0, 100, (i, loop) =>
            {
                Interlocked.Increment(ref k);
                var counter = new AtomicCounter();

                Assert.AreEqual(0, counter.Value);

                void Callback()
                {
                    counter.Increment();
                    global.Increment();
                }

                Parallel.Invoke(Callback, Callback, Callback, Callback, Callback, Callback, Callback, Callback, Callback, Callback, Callback, Callback, Callback);

                Assert.AreEqual(13, counter.Value);
            });

            Assert.AreEqual(100, k);
            Assert.AreEqual(1300, global.Value);
        }
コード例 #8
0
        /// <summary>
        /// Invalidates draw matrix and autosize caches.
        /// </summary>
        /// <returns>If the invalidate was actually necessary.</returns>
        public virtual bool Invalidate(Invalidation invalidation = Invalidation.All, Drawable source = null, bool shallPropagate = true)
        {
            if (invalidation == Invalidation.None)
            {
                return(false);
            }

            OnInvalidate?.Invoke();

            if (shallPropagate && Parent != null && source != Parent)
            {
                Parent.InvalidateFromChild(invalidation, this);
            }

            bool alreadyInvalidated = true;

            // Either ScreenSize OR ScreenPosition OR Colour
            if ((invalidation & (Invalidation.Geometry | Invalidation.Colour)) > 0)
            {
                if ((invalidation & Invalidation.SizeInParentSpace) > 0)
                {
                    alreadyInvalidated &= !boundingSizeBacking.Invalidate();
                }

                alreadyInvalidated &= !screenSpaceDrawQuadBacking.Invalidate();
                alreadyInvalidated &= !drawInfoBacking.Invalidate();
            }

            if (!alreadyInvalidated || (invalidation & Invalidation.DrawNode) > 0)
            {
                invalidationID = invalidationCounter.Increment();
            }

            return(!alreadyInvalidated);
        }
コード例 #9
0
        protected override void Decode(IChannelHandlerContext context, IByteBuffer input, List <object> output)
        {
            string msg = string.Empty;

            byte[] buffer = null;
            try
            {
                buffer = new byte[input.Capacity + 2];
                input.ReadBytes(buffer, 1, input.Capacity);
                buffer[0] = JT808.Protocol.JT808Package.BeginFlag;
                buffer[input.Capacity + 1] = JT808.Protocol.JT808Package.EndFlag;
                output.Add(new JT808RequestInfo(buffer));
                MsgSuccessCounter.Increment();
                if (logger.IsEnabled(LogLevel.Debug))
                {
                    logger.LogDebug("accept package success count<<<" + MsgSuccessCounter.Count.ToString());
                }
            }
            catch (Exception ex)
            {
                MsgFailCounter.Increment();
                logger.LogError("accept package fail count<<<" + MsgFailCounter.Count.ToString());
                logger.LogError(ex, "accept msg<<<" + msg);
                return;
            }
        }
コード例 #10
0
        public ClientStats GetStats(bool reset)
        {
            var histogramData = new HistogramData();

            foreach (var hist in threadLocalHistogram.Values)
            {
                hist.GetSnapshot(histogramData, reset);
            }

            var secondsElapsed = wallClockStopwatch.GetElapsedSnapshot(reset).TotalSeconds;

            if (reset)
            {
                statsResetCount.Increment();
            }

            GrpcEnvironment.Logger.Info("[ClientRunnerImpl.GetStats] GC collection counts: gen0 {0}, gen1 {1}, gen2 {2}, (histogram reset count:{3}, seconds since reset: {4})",
                                        GC.CollectionCount(0), GC.CollectionCount(1), GC.CollectionCount(2), statsResetCount.Count, secondsElapsed);

            // TODO: populate user time and system time
            return(new ClientStats
            {
                Latencies = histogramData,
                TimeElapsed = secondsElapsed,
                TimeUser = 0,
                TimeSystem = 0
            });
        }
コード例 #11
0
ファイル: ClientRunners.cs プロジェクト: NetProg-F2020/lab5
        public ClientStats GetStats(bool reset)
        {
            var histogramData = new HistogramData();

            foreach (var hist in threadLocalHistogram.Values)
            {
                hist.GetSnapshot(histogramData, reset);
            }

            var timeSnapshot = timeStats.GetSnapshot(reset);

            if (reset)
            {
                statsResetCount.Increment();
            }

            GrpcEnvironment.Logger.Info("[ClientRunnerImpl.GetStats] GC collection counts: gen0 {0}, gen1 {1}, gen2 {2}, (histogram reset count:{3}, seconds since reset: {4})",
                                        GC.CollectionCount(0), GC.CollectionCount(1), GC.CollectionCount(2), statsResetCount.Count, timeSnapshot.WallClockTime.TotalSeconds);

            return(new ClientStats
            {
                Latencies = histogramData,
                TimeElapsed = timeSnapshot.WallClockTime.TotalSeconds,
                TimeUser = timeSnapshot.UserProcessorTime.TotalSeconds,
                TimeSystem = timeSnapshot.PrivilegedProcessorTime.TotalSeconds
            });
        }
コード例 #12
0
        public async Task ParallelAsyncTest()
        {
            var counter = new AtomicCounter();
            await Enumerable.Range(1, 50).Select(i => Task.Run(() => counter.Increment())).WhenAll();

            Assert.Equal(50, counter.Value);
        }
コード例 #13
0
        /// <summary>
        /// Run an <seealso cref="IAgent"/>.
        /// <para>
        /// This method does not return until the run loop is stopped via <seealso cref="Dispose()"/>.
        /// </para>
        /// </summary>
        public void Run()
        {
            if (!_thread.CompareAndSet(null, Thread.CurrentThread))
            {
                return;
            }

            var idleStrategy = _idleStrategy;
            var agent        = _agent;

            while (_running)
            {
                try
                {
                    idleStrategy.Idle(agent.DoWork());
                }
                catch (ThreadInterruptedException)
                {
                }
                catch (Exception ex)
                {
                    _errorCounter?.Increment();

                    _errorHandler(ex);
                }
            }
        }
コード例 #14
0
 private void HandleError(Exception exception)
 {
     if (_isRunning)
     {
         _errorCounter?.Increment();
         _errorHandler(exception);
     }
 }
コード例 #15
0
 private int RunBody()
 {
     for (int i = 0; i < Iterations; i++)
     {
         sharedCounter.Increment();
     }
     return((int)sharedCounter.Count);
 }
コード例 #16
0
 internal static void FaissNativeInit()
 {
     if (!IsNativeShutdownAllowed && _nativeInitCounter.Count > 0)
     {
         return;
     }
     // Llmar metodo init de faiss
     _nativeInitCounter.Increment();
 }
コード例 #17
0
ファイル: Channel.cs プロジェクト: szzfstgit/grpc-1
        internal void AddCallReference(object call)
        {
            activeCallCounter.Increment();

            bool success = false;

            handle.DangerousAddRef(ref success);
            GrpcPreconditions.CheckState(success);
        }
コード例 #18
0
        public void ParallelTest()
        {
            var counter = new AtomicCounter();

            Parallel.For(0, 50, i =>
            {
                counter.Increment();
            });
            Assert.Equal(50, counter.Value);
        }
コード例 #19
0
        public void Increment_ThreadSafety()
        {
            const int Iterations = 100_000;

            var counter = new AtomicCounter();

            Parallel.For(0, Iterations, i =>
            {
                counter.Increment();
            });

            Assert.Equal(Iterations, counter.Value);
        }
コード例 #20
0
        public void Increment_ThreadSafety()
        {
            // Arrange
            const int Iterations = 100_000;

            var counter = new AtomicCounter();

            // Act
            Parallel.For(0, Iterations, i =>
            {
                counter.Increment();
            });

            // Assert
            counter.Value.Should().Be(Iterations);
        }
コード例 #21
0
ファイル: RetryTest.cs プロジェクト: weidmueller/grpc
        public async Task ServiceConfigRetryPolicy_AsyncUnaryCall()
        {
            var counter = new AtomicCounter();

            helper.UnaryHandler = new UnaryServerMethod <string, string>((request, context) =>
            {
                var attempt = counter.Increment();
                if (attempt <= 2)
                {
                    throw new RpcException(new Status(StatusCode.Unavailable, $"Attempt {attempt} failed on purpose"));
                }
                return(Task.FromResult("PASS"));
            });

            Assert.AreEqual("PASS", await Calls.AsyncUnaryCall(helper.CreateUnaryCall(), "abc"));
        }
コード例 #22
0
        public void Increment(string key)
        {
            _counters.AddOrUpdate(key,
                                  _ =>
            {
                AtomicCounter newInstance = new AtomicCounter();
                newInstance.Increment();

                return(newInstance);
            },
                                  (_, counter) =>
            {
                counter.Increment();

                return(counter);
            });
        }
コード例 #23
0
ファイル: RetryTest.cs プロジェクト: weidmueller/grpc
        public async Task ServiceConfigRetryPolicy_ServerStreaming()
        {
            var counter = new AtomicCounter();

            helper.ServerStreamingHandler = new ServerStreamingServerMethod <string, string>(async(request, responseStream, context) =>
            {
                var attempt = counter.Increment();
                if (attempt <= 2)
                {
                    throw new RpcException(new Status(StatusCode.Unavailable, $"Attempt {attempt} failed on purpose"));
                }
                await responseStream.WriteAllAsync(request.Split(new [] { ' ' }));
            });

            var call = Calls.AsyncServerStreamingCall(helper.CreateServerStreamingCall(), "A B C");

            CollectionAssert.AreEqual(new string[] { "A", "B", "C" }, await call.ResponseStream.ToListAsync());
            Assert.AreEqual(StatusCode.OK, call.GetStatus().StatusCode);
        }
コード例 #24
0
        private static DestinationHealth EvaluateHealthState(double threshold, HttpResponseMessage?response, AtomicCounter count)
        {
            DestinationHealth newHealth;

            if (response != null && response.IsSuccessStatusCode)
            {
                // Success
                count.Reset();
                newHealth = DestinationHealth.Healthy;
            }
            else
            {
                // Failure
                var currentFailureCount = count.Increment();
                newHealth = currentFailureCount < threshold ? DestinationHealth.Healthy : DestinationHealth.Unhealthy;
            }

            return(newHealth);
        }
コード例 #25
0
        public void CouldDispose()
        {
            var counter = 0;

            Assert.IsFalse(AtomicCounter.GetIsDisposed(ref counter));
            Assert.AreEqual(1, AtomicCounter.Increment(ref counter));
            Assert.AreEqual(2, AtomicCounter.Increment(ref counter));

            Assert.Throws <InvalidOperationException>(() => { AtomicCounter.Dispose(ref counter); });

            Assert.AreEqual(1, AtomicCounter.Decrement(ref counter));
            Assert.AreEqual(0, AtomicCounter.DecrementIfOne(ref counter));

            Assert.IsFalse(AtomicCounter.GetIsDisposed(ref counter));

            AtomicCounter.Dispose(ref counter);

            Assert.IsTrue(AtomicCounter.GetIsDisposed(ref counter));
        }
コード例 #26
0
        public ClientStats GetStats(bool reset)
        {
            var histogramData  = histogram.GetSnapshot(reset);
            var secondsElapsed = wallClockStopwatch.GetElapsedSnapshot(reset).TotalSeconds;

            if (reset)
            {
                statsResetCount.Increment();
            }

            // TODO: populate user time and system time
            return(new ClientStats
            {
                Latencies = histogramData,
                TimeElapsed = secondsElapsed,
                TimeUser = 0,
                TimeSystem = 0
            });
        }
コード例 #27
0
        /// <summary>
        /// Process the specified entry in a most optimal way according
        /// to the bundle settings.
        /// </summary>
        /// <param name="key">
        /// The entry key.
        /// </param>
        /// <param name="value">
        /// The entry value.
        /// </param>
        public void Process(Object key, Object value)
        {
            AtomicCounter counter  = m_countThreads;
            int           cThreads = (int)counter.Increment();

            try
            {
                if (cThreads < ThreadThreshold)
                {
                    IDictionary dictionary = new Hashtable();
                    dictionary.Add(key, value);
                    Bundling(dictionary);
                    return;
                }

                Bundle bundle;
                bool   isBurst;
                while (true)
                {
                    bundle = (Bundle)getOpenBundle();
                    lock (bundle)
                    {
                        if (bundle.IsOpen())
                        {
                            bool isFirst = bundle.Add(key, value);

                            isBurst = bundle.WaitForResults(isFirst);
                            break;
                        }
                    }
                }
                bundle.Process(isBurst, key, value);
            }
            finally
            {
                counter.Decrement();
            }
        }
コード例 #28
0
        internal void Init()
        {
            // we cannot acquire _poolUsersCounter via TryAcquireCounter because that method uses _poolUsersCounter
            var poolCounterPtr = (int *)_pinnedSpan.Data + 1;

            *poolCounterPtr   = 0;
            _poolUsersCounter = new AtomicCounter(poolCounterPtr);
            var _ = _poolUsersCounter.Increment();

            var len = _pinnedSpan.Length;

            for (int i = 2; i < len - 1; i++)
            {
                // ReSharper disable once PossibleStructMemberModificationOfNonVariableStruct
                _pinnedSpan[i] = ~(i + 1);
            }

            // ReSharper disable once PossibleStructMemberModificationOfNonVariableStruct
            _pinnedSpan[0] = ~2;

            // ReSharper disable once PossibleStructMemberModificationOfNonVariableStruct
            _pinnedSpan[len - 1] = ~0;
        }
コード例 #29
0
        public void CouldTryDispose()
        {
            var counter = 0;

            Assert.IsFalse(AtomicCounter.GetIsDisposed(ref counter));
            Assert.AreEqual(1, AtomicCounter.Increment(ref counter));
            Assert.AreEqual(2, AtomicCounter.Increment(ref counter));

            Assert.AreEqual(2, AtomicCounter.TryDispose(ref counter));

            Assert.AreEqual(1, AtomicCounter.Decrement(ref counter));
            Assert.AreEqual(0, AtomicCounter.DecrementIfOne(ref counter));

            Assert.IsFalse(AtomicCounter.GetIsDisposed(ref counter));

            Assert.AreEqual(0, AtomicCounter.TryDispose(ref counter));

            Assert.IsTrue(AtomicCounter.GetIsDisposed(ref counter));

            Assert.AreEqual(-1, AtomicCounter.TryDispose(ref counter));

            counter = AtomicCounter.Disposed - 1;

            Assert.Throws <InvalidOperationException>(() => { AtomicCounter.TryDispose(ref counter); });

            counter = AtomicCounter.Disposed | (123 << 24);

            Assert.AreEqual(-1, AtomicCounter.TryDispose(ref counter));

            Assert.AreEqual(AtomicCounter.Disposed | (123 << 24), counter);

            counter = (123 << 24);

            Assert.AreEqual(0, AtomicCounter.TryDispose(ref counter));

            Assert.AreEqual((123 << 24), counter & ~AtomicCounter.Disposed);
        }
コード例 #30
0
        public async Task NoUnobservedTaskExceptionForAbandonedStreamingResponse()
        {
            // Verify that https://github.com/grpc/grpc/issues/17458 has been fixed.
            // Create a streaming response call, then cancel it without reading all the responses
            // and check that no unobserved task exceptions have been thrown.

            var unobservedTaskExceptionCounter = new AtomicCounter();

            TaskScheduler.UnobservedTaskException += (sender, e) => {
                unobservedTaskExceptionCounter.Increment();
                Console.WriteLine("Detected unobserved task exception: " + e.Exception);
            };

            var bodySizes = new List <int> {
                10, 10, 10, 10, 10
            };
            var request = new StreamingOutputCallRequest {
                ResponseParameters = { bodySizes.Select((size) => new ResponseParameters {
                        Size = size
                    }) }
            };

            for (int i = 0; i < 50; i++)
            {
                Console.WriteLine($"Starting iteration {i}");
                using (var call = client.StreamingOutputCall(request))
                {
                    // Intentionally only read the first response (we know there's more)
                    // The call will be cancelled as soon as we leave the "using" statement.
                    var firstResponse = await call.ResponseStream.MoveNext();
                }
                // Make it more likely to trigger the "Unobserved task exception" warning
                GC.Collect();
            }

            Assert.AreEqual(0, unobservedTaskExceptionCounter.Count);
        }