コード例 #1
0
        public void DoubleWaitTest()
        {
            ParallelTestHelper.Repeat(delegate
            {
                Console.WriteLine("run");
                var evt  = new ManualResetEventSlim();
                var t    = Task.Factory.StartNew(() => evt.Wait(2000));
                var cntd = new CountdownEvent(2);

                bool r1 = false, r2 = false;
                ThreadPool.QueueUserWorkItem(delegate
                {
                    cntd.Signal();
                    r1 = t.Wait(1000);
                    Console.WriteLine("out 1 {0}", r1);
                    cntd.Signal();
                });
                ThreadPool.QueueUserWorkItem(delegate
                {
                    cntd.Signal();
                    r2 = t.Wait(1000);
                    Console.WriteLine("out 2 {0}", r2);
                    cntd.Signal();
                });

                cntd.Wait(2000);
                cntd.Reset();
                evt.Set();
                cntd.Wait(2000);
                Assert.IsTrue(r1);
                Assert.IsTrue(r2);
            }, 5);
        }
コード例 #2
0
        // Validates init, set, reset state transitions.
        private static void RunCountdownEventTest0_StateTrans(int initCount, int increms, bool takeAllAtOnce)
        {
            CountdownEvent ev = new CountdownEvent(initCount);

            Assert.AreEqual(initCount, ev.InitialCount);

            // Increment (optionally).
            for (int i = 1; i < increms + 1; i++)
            {
                ev.AddCount();
                Assert.AreEqual(initCount + i, ev.CurrentCount);
            }

            // Decrement until it hits 0.
            if (takeAllAtOnce)
            {
                ev.Signal(initCount + increms);
            }
            else
            {
                for (int i = 0; i < initCount + increms; i++)
                {
                    Assert.IsFalse(ev.IsSet, string.Format("  > error: latch is set after {0} signals", i));
                    ev.Signal();
                }
            }

            Assert.IsTrue(ev.IsSet);
            Assert.AreEqual(0, ev.CurrentCount);

            // Now reset the event and check its count.
            ev.Reset();
            Assert.AreEqual(ev.InitialCount, ev.CurrentCount);
        }
コード例 #3
0
        // Validates init, set, reset state transitions.
        private static void RunCountdownEventTest0_StateTrans(int initCount, int increms, bool takeAllAtOnce)
        {
            CountdownEvent ev = new CountdownEvent(initCount);

            Assert.Equal(initCount, ev.InitialCount);

            // Increment (optionally).
            for (int i = 1; i < increms + 1; i++)
            {
                ev.AddCount();
                Assert.Equal(initCount + i, ev.CurrentCount);
            }

            // Decrement until it hits 0.
            if (takeAllAtOnce)
            {
                ev.Signal(initCount + increms);
            }
            else
            {
                for (int i = 0; i < initCount + increms; i++)
                {
                    Assert.False(ev.IsSet, string.Format("  > error: latch is set after {0} signals", i));
                    ev.Signal();
                }
            }

            Assert.True(ev.IsSet);
            Assert.Equal(0, ev.CurrentCount);

            // Now reset the event and check its count.
            ev.Reset();
            Assert.Equal(ev.InitialCount, ev.CurrentCount);
        }
コード例 #4
0
ファイル: countdownevent.cs プロジェクト: ruo2012/samples-1
    static async Task Main()
    {
        // Initialize a queue and a CountdownEvent
        ConcurrentQueue <int> queue = new ConcurrentQueue <int>(Enumerable.Range(0, 10000));
        CountdownEvent        cde   = new CountdownEvent(10000); // initial count = 10000

        // This is the logic for all queue consumers
        Action consumer = () =>
        {
            int local;
            // decrement CDE count once for each element consumed from queue
            while (queue.TryDequeue(out local))
            {
                cde.Signal();
            }
        };

        // Now empty the queue with a couple of asynchronous tasks
        Task t1 = Task.Factory.StartNew(consumer);
        Task t2 = Task.Factory.StartNew(consumer);

        // And wait for queue to empty by waiting on cde
        cde.Wait(); // will return when cde count reaches 0

        Console.WriteLine("Done emptying queue.  InitialCount={0}, CurrentCount={1}, IsSet={2}",
                          cde.InitialCount, cde.CurrentCount, cde.IsSet);

        // Proper form is to wait for the tasks to complete, even if you that their work
        // is done already.
        await Task.WhenAll(t1, t2);

        // Resetting will cause the CountdownEvent to un-set, and resets InitialCount/CurrentCount
        // to the specified value
        cde.Reset(10);

        // AddCount will affect the CurrentCount, but not the InitialCount
        cde.AddCount(2);

        Console.WriteLine("After Reset(10), AddCount(2): InitialCount={0}, CurrentCount={1}, IsSet={2}",
                          cde.InitialCount, cde.CurrentCount, cde.IsSet);

        // Now try waiting with cancellation
        CancellationTokenSource cts = new CancellationTokenSource();

        cts.Cancel(); // cancels the CancellationTokenSource
        try
        {
            cde.Wait(cts.Token);
        }
        catch (OperationCanceledException)
        {
            Console.WriteLine("cde.Wait(preCanceledToken) threw OCE, as expected");
        }
        finally
        {
            cts.Dispose();
        }
        // It's good to release a CountdownEvent when you're done with it.
        cde.Dispose();
    }
コード例 #5
0
        public void Should_release_the_pool()
        {
            // Arrange
            var blockTheThread = new AutoResetEvent(false);
            var countdownEvent = new CountdownEvent(1);

            var queue = Substitute.For <IInMemoryPriorityQueue <GenericPriorityMessage <BasicDeliverEventArgs> > >();

            queue.When(x => x.Dequeue()).Do(callInfo => { countdownEvent.Signal(); blockTheThread.WaitOne(); });

            var consumer = new PriorityBurrowConsumer(Substitute.For <IModel>(), Substitute.For <IMessageHandler>(), Substitute.For <IRabbitWatcher>(), false, 1);

            consumer.Init(queue, Substitute.For <CompositeSubscription>(), 1, Guid.NewGuid().ToString());
            consumer.Ready();


            // Action
            countdownEvent.Wait();
            countdownEvent.Reset();
            blockTheThread.Set();
            consumer.MessageHandlerHandlingComplete(null);
            countdownEvent.Wait();
            // Assert

            queue.Received(2).Dequeue();
            consumer.Dispose();
            blockTheThread.Dispose();
        }
コード例 #6
0
        private static void TestSendReceiveRequestCore(IPEndPoint endPoint, int count, CountdownEvent latch)
        {
            using (var udpClient = new UdpClient(AddressFamily.InterNetwork))
            {
                udpClient.Connect(endPoint);

                for (int i = 0; i < count; i++)
                {
                    if (latch != null)
                    {
                        latch.Reset();
                    }

                    var ids = Enumerable.Repeat(0, latch == null ? 1 : latch.InitialCount).Select(_ => Guid.NewGuid().ToString()).ToArray();

                    if (!Task.WaitAll(
                            ids.Select(
                                id =>
                                Task.Factory.StartNew(
                                    _ =>
                    {
                        using (var buffer = new MemoryStream())
                        {
                            using (var packer = Packer.Create(buffer, false))
                            {
                                PackRequest(packer, id);
                            }

                            buffer.Position = 0;

                            if (latch != null)
                            {
                                latch.Signal();
                                if (!latch.Wait(Debugger.IsAttached ? Timeout.Infinite : TimeoutMilliseconds))
                                {
                                    throw new TimeoutException();
                                }
                            }

                            // send
                            udpClient.Send(buffer.ToArray(), ( int )buffer.Length);
                        }
                    },
                                    id
                                    )
                                ).ToArray(),
                            Debugger.IsAttached ? Timeout.Infinite : TimeoutMilliseconds
                            ))
                    {
                        throw new TimeoutException();
                    }

                    // receive
                    IPEndPoint received = endPoint;
                    var        result   = Unpacking.UnpackArray(udpClient.Receive(ref endPoint)).Value;
                    AssertResponse(result, ids);
                }
            }
        }
コード例 #7
0
        public void Start(DebugTarget target)
        {
            _updateSuspended = true;
            var channel  = target.KnownTool.GetChannel();
            var services = channel.GetRemoteServices().ToList();

            services.ForEach(service => channel.AddEventListener(service, this));

            _suspendBarrier.Reset();

            _notifyDebugEnterThread = new Thread(HandleNotifyDebugEnter)
            {
                Name = "HandleNotifyDebugEnter"
            };
            _notifyDebugEnterThread.Start();
            _server.DebuggerAttached += Server_DebuggerAttached;
        }
コード例 #8
0
        public void Start(IEventStoreConnection connection)
        {
            Require.NotNull(connection, "connection");

            m_connection = connection;
            m_listener.OnSubscriptionStarted(this);
            m_processingCountdown.Reset(1);
        }
コード例 #9
0
ファイル: SocketTests.cs プロジェクト: locus84/UnlitSocket
        public void TestCountEventTest()
        {
            var e = new CountdownEvent(0);

            e.Reset(2);
            e.AddCount(1);
            e.AddCount(1);
        }
コード例 #10
0
        /// <summary>
        /// Runs flops and inops calcuations in dedicated threads
        /// </summary>
        /// <param name="iterations">-1: run infinetely</param>
        /// <remarks>
        /// Using tasks may lead to pauses and stalling (tens of seconds), seems like snatdard schedulaer doesn't kick off all tasks right away and they keep waiting for a long time. No such problem with threads
        /// </remarks>
        ///<returns>Seconds it took to complete the calculations</returns>
        public Double RunXopsMultiThreaded(int iterations, int threads, bool inops = false, bool precision64Bit = false)
        {
            runningInMtMode = true;

            GC.Collect(GC.MaxGeneration, GCCollectionMode.Forced, true);

            mtBreakCalled     = false;
            threadLoopCounter = 0;

            thrds = new Thread[threads];

            threadsDoneCountdown.Reset(threads);
            threadsReadyCountdown.Reset(threads);
            startThreads.Reset();

            for (int i = 0; i < threads; i++)
            {
                // TODO, check values are properly passed to delefate for already created threads
                thrds[i] = new Thread(() => { SingleThreadBody(iterations, inops, precision64Bit); });
                thrds[i].IsBackground = true;
                thrds[i].Priority     = ThreadPriority.Lowest; // UI thread gets stalled on WPF
                thrds[i].Start();
            }

            threadsReadyCountdown.Wait();
            // Starting stopwatch after Set() leads to spkes in results on Windows, might be issue due to thread scheduling (starting timer might happer after thread is started)
            threadsStopwatch.Restart();
            startThreads.Set();

            if (iterations != -1)
            {
                threadsDoneCountdown.Wait();
                threadsStopwatch.Stop();

                var time = ((Double)threadsStopwatch.ElapsedTicks) / Stopwatch.Frequency;

                LastResultGigaOPS = TimeToGigaOPS(time, iterations, threads, inops);

                runningInMtMode = false;

                return(time);
            }

            return(-1);
        }
コード例 #11
0
        public void OnSubscriptionStarted(INotificationListenerSubscription subscription)
        {
            Require.NotNull(subscription, "subscription");

            AssertSubscriptionWasNotBound();

            m_subscription = subscription;
            m_processingCountdown.Reset(1);
        }
コード例 #12
0
        public void ResetTest()
        {
            var evt = new CountdownEvent(5);

            Assert.AreEqual(5, evt.CurrentCount);
            evt.Signal();
            Assert.AreEqual(4, evt.CurrentCount);
            evt.Reset();
            Assert.AreEqual(5, evt.CurrentCount);
            Assert.AreEqual(5, evt.InitialCount);
            evt.Signal();
            evt.Signal();
            Assert.AreEqual(3, evt.CurrentCount);
            Assert.AreEqual(5, evt.InitialCount);
            evt.Reset(10);
            Assert.AreEqual(10, evt.CurrentCount);
            Assert.AreEqual(10, evt.InitialCount);
        }
コード例 #13
0
ファイル: TestNode.cs.cs プロジェクト: sdanzan/kafka-sharp
        public void TestProduceRequiredAcks()
        {
            var connection = new Mock <IConnection>();
            var count      = new CountdownEvent(1);

            connection.Setup(c => c.ConnectAsync()).Returns(Success);
            connection.Setup(c => c.SendAsync(It.IsAny <int>(), It.IsAny <ReusableMemoryStream>(), It.IsAny <bool>()))
            .Returns(Success)
            .Callback(() => count.Signal());
            var node = new Node("Node", () => connection.Object,
                                new ProduceSerialization(new CommonResponse <ProducePartitionResponse>()),
                                new Configuration {
                ProduceBufferingTime = TimeSpan.FromMilliseconds(1), RequiredAcks = RequiredAcks.None
            }, 1);

            node.Produce(ProduceMessage.New("test", 0, new Message(), DateTime.UtcNow.AddDays(1)));
            count.Wait();

            connection.Verify(c => c.SendAsync(It.IsAny <int>(), It.IsAny <ReusableMemoryStream>(), false), Times.Once());
            connection.Verify(c => c.SendAsync(It.IsAny <int>(), It.IsAny <ReusableMemoryStream>(), true), Times.Never());

            node = new Node("Node", () => connection.Object,
                            new ProduceSerialization(new CommonResponse <ProducePartitionResponse>()),
                            new Configuration {
                ProduceBufferingTime = TimeSpan.FromMilliseconds(1), RequiredAcks = RequiredAcks.Leader
            }, 1);
            count.Reset();
            node.Produce(ProduceMessage.New("test", 0, new Message(), DateTime.UtcNow.AddDays(1)));
            count.Wait();

            connection.Verify(c => c.SendAsync(It.IsAny <int>(), It.IsAny <ReusableMemoryStream>(), true), Times.Once());

            node = new Node("Node", () => connection.Object,
                            new ProduceSerialization(new CommonResponse <ProducePartitionResponse>()),
                            new Configuration {
                ProduceBufferingTime = TimeSpan.FromMilliseconds(1), RequiredAcks = RequiredAcks.AllInSyncReplicas
            }, 1);
            count.Reset();
            node.Produce(ProduceMessage.New("test", 0, new Message(), DateTime.UtcNow.AddDays(1)));
            count.Wait();

            connection.Verify(c => c.SendAsync(It.IsAny <int>(), It.IsAny <ReusableMemoryStream>(), true), Times.Exactly(2));
            connection.Verify(c => c.SendAsync(It.IsAny <int>(), It.IsAny <ReusableMemoryStream>(), false), Times.Once());
        }
コード例 #14
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="threadCount">开多少线程</param>
        void RunMultiTask(int threadCount)
        {
            Stopwatch watch = Stopwatch.StartNew();

            long start = 0;

            long end = 0;

            var total = GetSourceHead();

            if (total == 0)
            {
                return;
            }

            var pageSize = (int)Math.Ceiling((Double)total / threadCount);

            cde.Reset(threadCount);

            Task[] tasks = new Task[threadCount];

            for (int i = 0; i < threadCount; i++)
            {
                start = i * pageSize;

                end = (i + 1) * pageSize - 1;

                if (end > total)
                {
                    end = total;
                }

                var obj = start + "|" + end;

                tasks[i] = Task.Factory.StartNew(j => new DownFile().DownTaskMulti(obj, url, dic, cde), obj);
            }

            Task.WaitAll(tasks);

            var targetFile = @"D:\work_y\test\" + url.Substring(url.LastIndexOf('/') + 1);

            FileStream fs = new FileStream(targetFile, FileMode.Create);

            var result = dic.Keys.OrderBy(i => i).ToList();

            foreach (var item in result)
            {
                fs.Write(dic[item], 0, dic[item].Length);
            }

            fs.Close();

            watch.Stop();

            Console.WriteLine("多线程:下载耗费时间:{0}", watch.Elapsed.TotalMilliseconds);
        }
コード例 #15
0
 /// <summary>
 /// Can be called either from GrandOutput.OnConfigurationClosing or from GrandOutput.ObtainChannel when the FlushLock is acquired.
 /// This sets the CountdownEvent to 1.
 /// </summary>
 internal void EnsureActive()
 {
     #if !net40
     Debug.Assert(Monitor.IsEntered(_flushLock));
     #endif
     if (_useLock.CurrentCount == 0)
     {
         _useLock.Reset(1);
     }
 }
コード例 #16
0
 public static void ForceAddCount(this CountdownEvent cde, int signalCount = 1)
 {
     lock (cde)
     {
         if (!cde.TryAddCount(signalCount))
         {
             cde.Reset(signalCount);
         }
     }
 }
コード例 #17
0
        /**
         * wait until the given sequence number has been acknowledged
         *
         * @throws InterruptedException
         */
        public void WaitForAck(long sequenceNumber)
        {
            while (!session.IsShutdown && !HaveAcknowledgementFor(sequenceNumber))
            {
                waitForSeqAckLatch.Reset();
                waitForSeqAckLatch.Wait(10);

                // waitForSeqAckLatch.get().await(10, TimeUnit.MILLISECONDS);
            }
        }
コード例 #18
0
ファイル: CameraControl.cs プロジェクト: CJCHEN1230/Nart
        /// <summary>
        /// 在此顯示區域無限循環
        /// </summary>
        private void DisplayLoop()
        {
            while (true)
            {
                _count.Wait();            //等到兩個擷取畫面各執行一次Signal()後才通過
                _count.Reset(2);          //重設定count為兩次

                Dispatcher.BeginInvoke(new ShowBufferDelegate(ShowImageBuffer));
            }
        }
コード例 #19
0
        public bool ExecuteStep()
        {
            _queue = new ConcurrentQueue <Func <bool> >(_tasks);
            countdown.Reset();
            Enumerable.Range(0, ThreadCount).ToList().ForEach(i => _resets[i].Set());

            countdown.Wait();

            return(haveMore);
        }
コード例 #20
0
        private async Task Disconnect()
        {
            reconnections.Reset(1);

            //Kill ongoing readers
            readerTokenSource?.Cancel();

            //Make sure reader moves to await reconnect
            await Task.Delay(250);

            await clientWebSocket?.CloseAsync(WebSocketCloseStatus.NormalClosure, "Reconnecting", generalTokenSource.Token);

            //We are disconnected - try to reconnect
            clientWebSocket?.Dispose();
            clientWebSocket = null;

            readerTokenSource?.Dispose();
            readerTokenSource = null;
        }
コード例 #21
0
 public override void UpdateDocument(Term term, IEnumerable <IIndexableField> doc, Analyzer analyzer)
 {
     base.UpdateDocument(term, doc, analyzer);
     if (waitAfterUpdate)
     {
         signal.Reset(signal.CurrentCount == 0 ? 0 : signal.CurrentCount - 1);
         latch.Wait();
     }
     // LUCENENET NOTE: No need to catch and rethrow same excepton type ThreadInterruptedException
 }
コード例 #22
0
        static void Main(string[] args)
        {
            FindDefaultThreadOnThreadPool();

            Console.WriteLine();
            Console.WriteLine();
            Console.WriteLine($"第 1 次,產生 {MaxEmulateThreads} 執行緒請求");
            EmulateMoreThreads((MaxEmulateThreads - MinThreadsOnThreadPool + 1) * 1000, (MaxEmulateThreads - MinThreadsOnThreadPool + 1) * 1000);
            Thread.Sleep(2000);
            Console.WriteLine();
            Console.WriteLine();

            Console.WriteLine($"第 2次,產生 {MaxEmulateThreads} 執行緒請求");
            Countdown.Reset();
            EmulateMoreThreads(5 * 1000, 5 * 1000);
            Thread.Sleep(2000);
            Console.WriteLine();
            Console.WriteLine();

            Console.WriteLine($"第 3次,產生 {MaxEmulateThreads} 執行緒請求,休息 {ThreadPoolCollectionTime1} 秒");
            Thread.Sleep(ThreadPoolCollectionTime1 * 1000);
            Countdown.Reset();
            EmulateMoreThreads((MaxEmulateThreads - MinThreadsOnThreadPool + 1) * 1000, (MaxEmulateThreads - MinThreadsOnThreadPool + 1) * 1000);
            Console.WriteLine();
            Console.WriteLine();
            Console.WriteLine($"休息 {ThreadPoolCollectionTime2} 秒,等候執行緒集區清空新建立的執行緒");
            Thread.Sleep(ThreadPoolCollectionTime2 * 1000);
            Console.WriteLine();
            Console.WriteLine();

            Console.WriteLine($"第 4次,產生 {MaxEmulateThreads} 執行緒請求");
            ThreadsOnThreadPool.Clear();
            FindDefaultThreadOnThreadPool();
            Countdown.Reset();
            EmulateMoreThreads((MaxEmulateThreads - MinThreadsOnThreadPool + 1) * 1000, (MaxEmulateThreads - MinThreadsOnThreadPool + 1) * 1000);
            Thread.Sleep(2000);
            Console.WriteLine();
            Console.WriteLine();

            Console.WriteLine("Press any key for continuing...");
            Console.ReadKey();
        }
コード例 #23
0
 void createThreads()
 {
     //Console.WriteLine ($"count down reset");
     countdown.Reset();
     for (int i = 0; i < threadCount; i++)
     {
         Thread t = new Thread(drawingThread);
         t.IsBackground = true;
         t.Start();
     }
 }
コード例 #24
0
        private void BiscuitMakerJob(CancellationToken cancellationToken)
        {
            while (true)
            {
                if (cancellationToken.IsCancellationRequested)
                {
                    lineIsEmptyEvent.Wait();
                    DispatchTurnedOffMessage();
                    cancellationToken.ThrowIfCancellationRequested();
                }

                rotationsCountdown.Wait();
                rotationsCountdown.Reset();
                DispatchMessage("Extruder puts 1 biscuit");
                rotationsCountdown.Wait();
                rotationsCountdown.Reset();
                DispatchMessage("Stamper stamps 1 biscuit");
                newBiscuitOnTheLine.Set();
            }
        }
コード例 #25
0
        public void ShouldStopPullingTaskWhenSubscriptionIsDeleted()
        {
            using (var store = GetDocumentStore())
            {
                // insert few documents and fetch them using subscription
                using (var session = store.OpenSession())
                {
                    for (int i = 0; i < 10; i++)
                    {
                        session.Store(new Company());
                    }

                    session.SaveChanges();
                }

                var id = store.Subscriptions.Create <Company>();

                var subscription = store.Subscriptions.GetSubscriptionWorker(new SubscriptionWorkerOptions(id)
                {
                    MaxDocsPerBatch = 5,
                    TimeToWaitBeforeConnectionRetry = TimeSpan.FromSeconds(5)
                });

                var docs = new CountdownEvent(10);

                subscription.Run(batch => batch.Items.ForEach(x =>
                {
                    docs.Signal();
                }));

                Assert.True(docs.Wait(TimeSpan.FromSeconds(15)));

                // all documents were fetched - time to delete subscription

                store.Subscriptions.Delete(id);

                // verify if we don't get new items

                docs.Reset(1);

                using (var session = store.OpenSession())
                {
                    for (int i = 0; i < 2; i++)
                    {
                        session.Store(new Company());
                    }

                    session.SaveChanges();
                }

                // wait a bit for new documents - we shouldn't get any
                Assert.False(docs.Wait(50));
            }
        }
コード例 #26
0
        public void Reset_Zero()
        {
            var ev = new CountdownEvent(1);

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

            ev.Reset(0);
            Assert.IsTrue(ev.IsSet, "#2");
            Assert.IsTrue(ev.Wait(0), "#3");
            Assert.AreEqual(0, ev.CurrentCount, "#4");
        }
コード例 #27
0
        public void Reset_Invalid()
        {
            var ev = new CountdownEvent(1);

            try {
                ev.Reset(-1);
                Assert.Fail("#1");
            } catch (ArgumentOutOfRangeException) {
                Assert.AreEqual(1, ev.CurrentCount, "#1a");
            }
        }
コード例 #28
0
        private void UT_SubscribeToEvents(RedisContext context, IList <KeyEvent> expectedEvents, KeyEventSubscriptionType?eventSubscriptionType = null, string key = null, KeyEvent?eventType = null)
        {
            ConcurrentQueue <KeyValuePair <string, KeyEvent> > result = new ConcurrentQueue <KeyValuePair <string, KeyEvent> >();
            CountdownEvent            handle = new CountdownEvent(expectedEvents.Count);
            Action <string, KeyEvent> action = (k, e) =>
            {
                result.Enqueue(new KeyValuePair <string, KeyEvent>(k, e));
                handle.Signal();
            };

            Action unsubscribeAction = () => { };

            if (key == null && !eventType.HasValue && eventSubscriptionType.HasValue)
            {
                context.KeyEvents.Subscribe(eventSubscriptionType.Value, action);
                unsubscribeAction = () => context.KeyEvents.Unsubscribe(eventSubscriptionType.Value);
            }
            else if (key != null)
            {
                context.KeyEvents.Subscribe(key, action);
                unsubscribeAction = () => context.KeyEvents.Unsubscribe(key);
            }
            else if (eventType.HasValue)
            {
                context.KeyEvents.Subscribe(eventType.Value, action);
                unsubscribeAction = () => context.KeyEvents.Unsubscribe(eventType.Value);
            }

            var objectKey = key ?? Guid.NewGuid().ToString();

            context.Cache.SetObject(objectKey, new { Name = "alex", Created = DateTime.UtcNow });
            Thread.Sleep(500);
            context.Cache.Remove(objectKey);

            Assert.IsTrue(handle.Wait(5000));
            Assert.AreEqual(expectedEvents.Count, result.Count);

            foreach (var expectedEvent in expectedEvents)
            {
                KeyValuePair <string, KeyEvent> e;
                Assert.IsTrue(result.TryDequeue(out e));
                Assert.AreEqual(expectedEvent, e.Value);
                Assert.AreEqual(objectKey, e.Key);
            }

            //Now test Unsubscribe. No more events should be received in queue and handle will timeout.
            handle.Reset(1);
            unsubscribeAction();
            context.Cache.SetObject(objectKey, new { Name = "alex", Created = DateTime.UtcNow }, TimeSpan.FromMilliseconds(500));
            Assert.IsFalse(handle.Wait(1000));
            Assert.IsTrue(result.IsEmpty);

            context.KeyEvents.Unsubscribe(KeyEventSubscriptionType.All);
        }
 public static void Increment(this CountdownEvent @event)
 {
     if (@event.IsSet)
     {
         @event.Reset(1);
     }
     else
     {
         @event.AddCount();
     }
 }
コード例 #30
0
        public void WaitDone()
        {
            // take out initialization value of 1
            countdownThreads.Signal();

            // wait until we drain completely to zero
            countdownThreads.Wait();

            // Reset start in preparation for possible next round of work items
            countdownThreads.Reset();
        }
コード例 #31
0
        public static void RunCountdownEventTest2_Exceptions()
        {
            CountdownEvent cde = null;

            Assert.Throws <ArgumentOutOfRangeException>(() => cde = new CountdownEvent(-1));
            // Failure Case: Constructor didn't throw AORE when -1 passed

            cde = new CountdownEvent(1);
            Assert.Throws <ArgumentOutOfRangeException>(() => cde.Signal(0));
            // Failure Case: Signal didn't throw AORE when 0 passed

            cde = new CountdownEvent(0);
            Assert.Throws <InvalidOperationException>(() => cde.Signal());
            // Failure Case: Signal didn't throw IOE when the count is zero

            cde = new CountdownEvent(1);
            Assert.Throws <InvalidOperationException>(() => cde.Signal(2));
            // Failure Case: Signal didn't throw IOE when the signal count > current count

            Assert.Throws <ArgumentOutOfRangeException>(() => cde.AddCount(0));
            // Failure Case: AddCount didn't throw AORE when 0 passed

            cde = new CountdownEvent(0);
            Assert.Throws <InvalidOperationException>(() => cde.AddCount(1));
            // Failure Case: AddCount didn't throw IOE when the count is zero

            cde = new CountdownEvent(int.MaxValue - 10);
            Assert.Throws <InvalidOperationException>(() => cde.AddCount(20));
            // Failure Case: AddCount didn't throw IOE when the count > int.Max

            cde = new CountdownEvent(2);
            Assert.Throws <ArgumentOutOfRangeException>(() => cde.Reset(-1));
            // Failure Case: Reset didn't throw AORE when the count is zero

            Assert.Throws <ArgumentOutOfRangeException>(() => cde.Wait(-2));
            // Failure Case: Wait(int) didn't throw AORE when the totalmilliseconds < -1

            Assert.Throws <ArgumentOutOfRangeException>(() => cde.Wait(TimeSpan.FromDays(-1)));
            // Failure Case:  FAILED.  Wait(TimeSpan) didn't throw AORE when the totalmilliseconds < -1

            Assert.Throws <ArgumentOutOfRangeException>(() => cde.Wait(TimeSpan.MaxValue));
            // Failure Case: Wait(TimeSpan, CancellationToken) didn't throw AORE when the totalmilliseconds > int.max

            Assert.Throws <ArgumentOutOfRangeException>(() => cde.Wait(TimeSpan.FromDays(-1), new CancellationToken()));
            // Failure Case: Wait(TimeSpan) didn't throw AORE when the totalmilliseconds < -1

            Assert.Throws <ArgumentOutOfRangeException>(() => cde.Wait(TimeSpan.MaxValue, new CancellationToken()));
            // Failure Case: Wait(TimeSpan, CancellationToken) didn't throw AORE when the totalmilliseconds > int.max

            cde.Dispose();

            Assert.Throws <ObjectDisposedException>(() => cde.Wait());
            // Failure Case: Wait() didn't throw ODE after Dispose
        }
コード例 #32
0
ファイル: EtwTests.cs プロジェクト: SGuyGe/corefx
        public void TestEtw()
        {
            using (var listener = new TestEventListener(new Guid("16F53577-E41D-43D4-B47E-C17025BF4025"), EventLevel.Verbose))
            {
                ActionBlock<int> ab = null;
                BufferBlock<int> bb = null;
                int remaining = 0;
                CountdownEvent ce = new CountdownEvent(0);

                // Check that block creation events fire
                const int DataflowBlockCreatedId = 1;
                remaining = 2;
                listener.RunWithCallback(ev => {
                        Assert.Equal(expected: DataflowBlockCreatedId, actual: ev.EventId);
                        remaining--;
                    },
                    () => {
                        ab = new ActionBlock<int>(i => { });
                        bb = new BufferBlock<int>(); // trigger block creation event
                        Assert.Equal(expected: 0, actual: remaining);
                    });

                // Check that linking events fire
                const int BlockLinkedId = 4;
                remaining = 1;
                IDisposable link = null;
                listener.RunWithCallback(ev => {
                        Assert.Equal(expected: BlockLinkedId, actual: ev.EventId);
                        remaining--;
                    },
                    () => {
                        link = bb.LinkTo(ab);
                        Assert.Equal(expected: 0, actual: remaining);
                    });

                // Check that unlinking events fire
                const int BlockUnlinkedId = 5;
                remaining = 1;
                listener.RunWithCallback(ev => {
                        Assert.Equal(expected: BlockUnlinkedId, actual: ev.EventId);
                        remaining--;
                    },
                    () => {
                        link.Dispose();
                        Assert.Equal(expected: 0, actual: remaining);
                    });

                // Check that task launched events fire
                const int TaskLaunchedId = 2;
                ce.Reset(1);
                listener.RunWithCallback(ev => {
                        Assert.Equal(expected: TaskLaunchedId, actual: ev.EventId);
                        ce.Signal();
                    },
                    () => {
                        ab.Post(42);
                        ce.Wait();
                        Assert.Equal(expected: 0, actual: ce.CurrentCount);
                    });

                // Check that completion events fire
                const int BlockCompletedId = 3;
                ce.Reset(2);
                listener.RunWithCallback(ev => {
                        Assert.Equal(expected: BlockCompletedId, actual: ev.EventId);
                        ce.Signal();
                    },
                    () => {
                        ab.Complete();
                        bb.Complete();
                        ce.Wait();
                        Assert.Equal(expected: 0, actual: ce.CurrentCount);
                    });

            }
        }
コード例 #33
0
        public static void RunCountdownEventTest2_Exceptions()
        {
            CountdownEvent cde = null;
            Assert.Throws<ArgumentOutOfRangeException>(() => cde = new CountdownEvent(-1));
            // Failure Case: Constructor didn't throw AORE when -1 passed

            cde = new CountdownEvent(1);
            Assert.Throws<ArgumentOutOfRangeException>(() => cde.Signal(0));
            // Failure Case: Signal didn't throw AORE when 0 passed

            cde = new CountdownEvent(0);
            Assert.Throws<InvalidOperationException>(() => cde.Signal());
            // Failure Case: Signal didn't throw IOE when the count is zero

            cde = new CountdownEvent(1);
            Assert.Throws<InvalidOperationException>(() => cde.Signal(2));
            // Failure Case: Signal didn't throw IOE when the signal count > current count

            Assert.Throws<ArgumentOutOfRangeException>(() => cde.AddCount(0));
            // Failure Case: AddCount didn't throw AORE when 0 passed

            cde = new CountdownEvent(0);
            Assert.Throws<InvalidOperationException>(() => cde.AddCount(1));
            // Failure Case: AddCount didn't throw IOE when the count is zero

            cde = new CountdownEvent(int.MaxValue - 10);
            Assert.Throws<InvalidOperationException>(() => cde.AddCount(20));
            // Failure Case: AddCount didn't throw IOE when the count > int.Max

            cde = new CountdownEvent(2);
            Assert.Throws<ArgumentOutOfRangeException>(() => cde.Reset(-1));
            // Failure Case: Reset didn't throw AORE when the count is zero

            Assert.Throws<ArgumentOutOfRangeException>(() => cde.Wait(-2));
            // Failure Case: Wait(int) didn't throw AORE when the totalmilliseconds < -1

            Assert.Throws<ArgumentOutOfRangeException>(() => cde.Wait(TimeSpan.FromDays(-1)));
            // Failure Case:  FAILED.  Wait(TimeSpan) didn't throw AORE when the totalmilliseconds < -1

            Assert.Throws<ArgumentOutOfRangeException>(() => cde.Wait(TimeSpan.MaxValue));
            // Failure Case: Wait(TimeSpan, CancellationToken) didn't throw AORE when the totalmilliseconds > int.max

            Assert.Throws<ArgumentOutOfRangeException>(() => cde.Wait(TimeSpan.FromDays(-1), new CancellationToken()));
            // Failure Case: Wait(TimeSpan) didn't throw AORE when the totalmilliseconds < -1

            Assert.Throws<ArgumentOutOfRangeException>(() => cde.Wait(TimeSpan.MaxValue, new CancellationToken()));
            // Failure Case: Wait(TimeSpan, CancellationToken) didn't throw AORE when the totalmilliseconds > int.max

            cde.Dispose();

            Assert.Throws<ObjectDisposedException>(() => cde.Wait());
            // Failure Case: Wait() didn't throw ODE after Dispose
        }