当前位置: 首页>>代码示例>>C#>>正文


C# CountdownEvent.Wait方法代码示例

本文整理汇总了C#中System.Threading.CountdownEvent.Wait方法的典型用法代码示例。如果您正苦于以下问题:C# CountdownEvent.Wait方法的具体用法?C# CountdownEvent.Wait怎么用?C# CountdownEvent.Wait使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在System.Threading.CountdownEvent的用法示例。


在下文中一共展示了CountdownEvent.Wait方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: Should_release_the_pool

        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();
        }
开发者ID:sovanesyan,项目名称:Burrow.NET,代码行数:26,代码来源:MethodMessageHandlerHandlingComplete.cs

示例2: Remove_WhenConcurrentDeletesUsingDtc_OnlyOneOperationShouldSucceed

        public async Task Remove_WhenConcurrentDeletesUsingDtc_OnlyOneOperationShouldSucceed()
        {
            var persister = new TimeoutPersister(store);
            var timeoutData = new TimeoutData();
            await persister.Add(timeoutData, new ContextBag());

            var documentRemoved = new CountdownEvent(2);

            var t1 = Task.Run(async () =>
            {
                using (var tx = new TransactionScope(TransactionScopeOption.RequiresNew, TransactionScopeAsyncFlowOption.Enabled))
                {
                    var result = await persister.TryRemove(timeoutData.Id, new ContextBag());
                    documentRemoved.Signal(1);
                    documentRemoved.Wait();
                    tx.Complete();
                    return result;
                }
            });

            var t2 = Task.Run(async () =>
            {
                using (var tx = new TransactionScope(TransactionScopeOption.RequiresNew, TransactionScopeAsyncFlowOption.Enabled))
                {
                    var result = await persister.TryRemove(timeoutData.Id, new ContextBag());
                    documentRemoved.Signal(1);
                    documentRemoved.Wait();
                    tx.Complete();
                    return result;
                }
            });

            Assert.IsTrue(await t1 | await t2, "the document should be deleted");
            Assert.IsFalse(t1.Result && t2.Result, "only one operation should complete successfully");
        }
开发者ID:areicher,项目名称:NServiceBus.RavenDB,代码行数:35,代码来源:When_removing_timeouts_from_storage.cs

示例3: be_able_to_subscribe_to_non_existing_stream

        public void be_able_to_subscribe_to_non_existing_stream()
        {
            const string stream = "be_able_to_subscribe_to_non_existing_stream";
            using (var store = BuildConnection(_node))
            {
                store.ConnectAsync().Wait();
                var appeared = new ManualResetEventSlim(false);
                var dropped = new CountdownEvent(1);

                var subscription = store.SubscribeToStreamFrom(stream,
                                                               null,
                                                               CatchUpSubscriptionSettings.Default,
                                                               (_, x) => appeared.Set(),
                                                               _ => Log.Info("Live processing started."),
                                                               (_, __, ___) => dropped.Signal());

                Thread.Sleep(100); // give time for first pull phase
                store.SubscribeToStreamAsync(stream, false, (s, x) => { }, (s, r, e) => { }).Wait();
                Thread.Sleep(100);
                Assert.IsFalse(appeared.Wait(0), "Some event appeared.");
                Assert.IsFalse(dropped.Wait(0), "Subscription was dropped prematurely.");
                subscription.Stop(Timeout);
                Assert.IsTrue(dropped.Wait(Timeout));
            }
        }
开发者ID:czcz1024,项目名称:EventStore,代码行数:25,代码来源:subscribe_to_stream_catching_up_should.cs

示例4: ExecuteLevel

 protected override void ExecuteLevel(IList<Computation> computationsOfLevel)
 {
     using (var countEvent = new CountdownEvent(1))
     {
         foreach (var item in computationsOfLevel)
         {
             var cc = item.Context as ParallelComputationContext;
             if (cc != null)
             {
                 countEvent.AddCount();
                 cc.RunTransform(() =>
                 {
                     item.Transform();
                     countEvent.Signal();
                 });
             }
             else
             {
                 countEvent.Signal();
                 countEvent.Wait();
                 item.Transform();
                 countEvent.Reset();
             }
             OnComputationCompleted(new ComputationEventArgs(item));
         }
         countEvent.Signal();
         countEvent.Wait();
     }
 }
开发者ID:FrederikP,项目名称:NMF,代码行数:29,代码来源:ParallelTransformationContext2.cs

示例5: ManualResetEventSlim_SetAfterDisposeTest

        public void ManualResetEventSlim_SetAfterDisposeTest()
        {
            ManualResetEventSlim mre = new ManualResetEventSlim();

            ParallelTestHelper.Repeat(delegate
            {
                Exception disp = null, setting = null;

                CountdownEvent evt = new CountdownEvent(2);
                CountdownEvent evtFinish = new CountdownEvent(2);

                Task.Factory.StartNew(delegate
                {
                    try
                    {
                        evt.Signal();
                        evt.Wait(1000);
                        mre.Dispose();
                    }
                    catch (Exception e)
                    {
                        disp = e;
                    }
                    evtFinish.Signal();
                });
                Task.Factory.StartNew(delegate
                {
                    try
                    {
                        evt.Signal();
                        evt.Wait(1000);
                        mre.Set();
                    }
                    catch (Exception e)
                    {
                        setting = e;
                    }
                    evtFinish.Signal();
                });

                bool bb = evtFinish.Wait(1000);
                if (!bb)
                    Assert.AreEqual(true, evtFinish.IsSet);

                Assert.IsTrue(bb, "#0");
                Assert.IsNull(disp, "#1");
                Assert.IsNull(setting, "#2");

                evt.Dispose();
                evtFinish.Dispose();
            });
        }
开发者ID:mesheets,项目名称:Theraot-CF,代码行数:52,代码来源:WorkTest.cs

示例6: everything_should_go_fine

        public void everything_should_go_fine()
        {
            var miniNode = new MiniNode(PathName);
            miniNode.Start();

            var tcpPort = miniNode.TcpEndPoint.Port;
            var tcpSecPort = miniNode.TcpSecEndPoint.Port;
            var httpPort = miniNode.HttpEndPoint.Port;
            const int cnt = 50;
            var countdown = new CountdownEvent(cnt);

            // --- first part of events
            WriteEvents(cnt, miniNode, countdown);
            Assert.IsTrue(countdown.Wait(TimeSpan.FromSeconds(10)), "Too long writing first part of events.");
            countdown.Reset();

            // -- set up truncation
            var truncatePosition = miniNode.Db.Config.WriterCheckpoint.ReadNonFlushed();
            miniNode.Db.Config.TruncateCheckpoint.Write(truncatePosition);
            miniNode.Db.Config.TruncateCheckpoint.Flush();

            // --- second part of events
            WriteEvents(cnt, miniNode, countdown);
            Assert.IsTrue(countdown.Wait(TimeSpan.FromSeconds(10)), "Too long writing second part of events.");
            countdown.Reset();

            miniNode.Shutdown(keepDb: true, keepPorts: true);

            // --- first restart and truncation
            miniNode = new MiniNode(PathName, tcpPort, tcpSecPort, httpPort);
            
            miniNode.Start();
            Assert.AreEqual(-1, miniNode.Db.Config.TruncateCheckpoint.Read());
            Assert.That(miniNode.Db.Config.WriterCheckpoint.Read(), Is.GreaterThanOrEqualTo(truncatePosition));

            // -- third part of events
            WriteEvents(cnt, miniNode, countdown);
            Assert.IsTrue(countdown.Wait(TimeSpan.FromSeconds(10)), "Too long writing third part of events.");
            countdown.Reset();

            miniNode.Shutdown(keepDb: true, keepPorts: true);

            // -- second restart
            miniNode = new MiniNode(PathName, tcpPort, tcpSecPort, httpPort);
            Assert.AreEqual(-1, miniNode.Db.Config.TruncateCheckpoint.Read());
            miniNode.Start();

            // -- if we get here -- then everything is ok
            miniNode.Shutdown();
        }
开发者ID:jjvdangelo,项目名称:EventStore,代码行数:50,代码来源:when_truncating_database.cs

示例7: HydratingFromMultipleThreads_IsSafe

        public void HydratingFromMultipleThreads_IsSafe()
        {
            var numberOfHydrations = 0;
            var cache = new CachedValue<int>(() => ++numberOfHydrations);

            Assert.That(cache.Value, Is.EqualTo(1));

            using (var countdownEvent = new CountdownEvent(2))
            {
                Action threadAction = () =>
                {
                    cache.Invalidate();
                    countdownEvent.Signal();
                    countdownEvent.Wait();

                    Assert.That(cache.Value, Is.EqualTo(2));
                };

                var t1 = threadAction.BeginInvoke(threadAction.EndInvoke, null);
                var t2 = threadAction.BeginInvoke(threadAction.EndInvoke, null);
                WaitHandle.WaitAll(new[]{t1.AsyncWaitHandle, t2.AsyncWaitHandle});
            }

            Assert.That(numberOfHydrations, Is.EqualTo(2));
        }
开发者ID:resnikb,项目名称:GitWorkflows,代码行数:25,代码来源:CachedValueTests.cs

示例8: Main

        static void Main(string[] args)
        {
            // If using an API key
            //ImportIO io = new ImportIO("http://api.import.io",Guid.parse("d08d14f3-6c98-44af-a301-f8d4288ecce3"),"tMFNJzaaLe8sgYF9hFNhKI7akyiPLMhfu8U2omNVCVr5hqWWLyiQMApDDyUucQKF++BAoVi6jnGnavYqRKP/9g==");
            
            // If using a username and password
            ImportIO io = new ImportIO();
            io.Login("xxx", "xxx");
            

            io.Connect();
            Dictionary<String,Object> query1 = new Dictionary<string,object>();
            query1.Add("input",new Dictionary<String,String>() {{ "query","mac mini" }});
            query1.Add("connectorGuids", new List<String>() { "39df3fe4-c716-478b-9b80-bdbee43bfbde" });

            Dictionary<String, Object> query2 = new Dictionary<string, object>();
            query2.Add("input", new Dictionary<String, String>() { { "query", "ubuntu" } });
            query2.Add("connectorGuids", new List<String>() { "39df3fe4-c716-478b-9b80-bdbee43bfbde" });

            Dictionary<String, Object> query3 = new Dictionary<string, object>();
            query3.Add("input", new Dictionary<String, String>() { { "query", "ibm" } });
            query3.Add("connectorGuids", new List<String>() { "39df3fe4-c716-478b-9b80-bdbee43bfbde" });

            countdownLatch = new CountdownEvent(3);

            io.DoQuery(query1, HandleQuery);
            io.DoQuery(query2, HandleQuery);
            io.DoQuery(query3, HandleQuery);

            countdownLatch.Wait();

            io.Disconnect();
        }
开发者ID:ksiomelo,项目名称:importio-client-libs,代码行数:33,代码来源:Program.cs

示例9: TestChangeNotification

        public void TestChangeNotification()
        {
            var countDown = new CountdownEvent(1);
            EventHandler<DatabaseChangeEventArgs> handler
                = (sender, e) => countDown.Signal();

            database.Changed += handler;

            // create a document
            var documentProperties = new Dictionary<string, object>();
            documentProperties["foo"] = 1;
            documentProperties["bar"] = false;
            documentProperties["baz"] = "touch";
            
            var body = new Body(documentProperties);
            var rev1 = new RevisionInternal(body);

            database.PutRevision(rev1, null, false);
            Sleep(500);
            
            Assert.IsTrue(countDown.Wait(TimeSpan.FromSeconds(1)));

            // Analysis disable once DelegateSubtraction
            database.Changed -= handler;
        }
开发者ID:jonfunkhouser,项目名称:couchbase-lite-net,代码行数:25,代码来源:ChangesTest.cs

示例10: TestFindAllEntities

        public void TestFindAllEntities()
        {
            RunAndAwait( () =>
            {
              var entities = new List<FindAllEntityAsync>();
              var latch = new CountdownEvent( 10 );
              for( int i = 0; i < 10; i++ )
              {
            var findAllEntity = new FindAllEntityAsync {Name = "bot_#" + i, Age = 20 + i};
            Backendless.Persistence.Save( findAllEntity, new AsyncCallback<FindAllEntityAsync>( response =>
              {
                entities.Add( findAllEntity );
                latch.Signal();
              }, fault =>
                {
                  for( int j = 0; j < latch.CurrentCount; j++ )
                    latch.Signal();

                  FailCountDownWith( fault );
                } ) );
              }
              latch.Wait();

              Backendless.Persistence.Of<FindAllEntityAsync>()
                     .Find( new ResponseCallback<BackendlessCollection<FindAllEntityAsync>>( this )
                       {
                         ResponseHandler =
                           backendlessCollection => AssertArgumentAndResultCollections( entities, backendlessCollection )
                       } );
            } );
        }
开发者ID:fturner19,项目名称:Unity-SDK,代码行数:31,代码来源:FindObjectTest.cs

示例11: ExecuteReadWithParallel

        protected PerformanceRecord ExecuteReadWithParallel(string operation, IEnumerable<uint> ids, int numberOfThreads, Func<long> readAction)
        {
            var countdownEvent = new CountdownEvent(numberOfThreads);

            var sw = Stopwatch.StartNew();
            var bytes = new long[numberOfThreads];
            for (int i = 0; i < numberOfThreads; i++)
            {
                var c = i;
                ThreadPool.QueueUserWorkItem(
                    state =>
                    {
                        bytes[c] = readAction();

                        countdownEvent.Signal();
                    });
            }

            countdownEvent.Wait();
            sw.Stop();

            return new PerformanceRecord
            {
                Bytes = bytes.Sum(),
                Operation = operation,
                Time = DateTime.Now,
                Duration = sw.ElapsedMilliseconds,
                ProcessedItems = ids.Count() * numberOfThreads
            };
        }
开发者ID:mattwarren,项目名称:LinqToMemory,代码行数:30,代码来源:StoragePerformanceTestBase.cs

示例12: ShouldInterruptDuringBusySpin

        public void ShouldInterruptDuringBusySpin()
        {
            const long expectedNumberMessages = 10;
            FillRingBuffer(expectedNumberMessages);

            var signal = new CountdownEvent(3);
            var sequence1 = new CountDownEventSequence(8L, signal);
            var sequence2 = new CountDownEventSequence(8L, signal);
            var sequence3 = new CountDownEventSequence(8L, signal);

            _eventProcessorMock1.Setup(x => x.Sequence).Returns(sequence1);
            _eventProcessorMock2.Setup(x => x.Sequence).Returns(sequence2);
            _eventProcessorMock3.Setup(x => x.Sequence).Returns(sequence3);

            var sequenceBarrier = _ringBuffer.NewBarrier(Util.GetSequencesFor(_eventProcessorMock1.Object, _eventProcessorMock2.Object, _eventProcessorMock3.Object));

            var alerted = false;
            var t = Task.Factory.StartNew(() =>
                                  {
                                      try
                                      {
                                          sequenceBarrier.WaitFor(expectedNumberMessages - 1);
                                      }
                                      catch (AlertException)
                                      {
                                          alerted = true;
                                      }
                                  });

            signal.Wait(TimeSpan.FromSeconds(3));
            sequenceBarrier.Alert();
            t.Wait();

            Assert.That(alerted, Is.True, "Thread was not interrupted");
        }
开发者ID:disruptor-net,项目名称:Disruptor-net,代码行数:35,代码来源:SequenceBarrierTests.cs

示例13: ExecuteWriteWithParallel

        protected List<PerformanceRecord> ExecuteWriteWithParallel(IEnumerable<TestData> data, int numberOfTransactions, int itemsPerTransaction, int numberOfThreads, Func<IEnumerator<TestData>, long, long, List<PerformanceRecord>> writeFunction, out long elapsedMilliseconds)
        {
            var countdownEvent = new CountdownEvent(numberOfThreads);

            var parallelData = SplitData(data, numberOfTransactions, itemsPerTransaction, numberOfThreads);

            var records = new List<PerformanceRecord>[numberOfThreads];
            var sw = Stopwatch.StartNew();

            for (int i = 0; i < numberOfThreads; i++)
            {
                ThreadPool.QueueUserWorkItem(
                    state =>
                    {
                        var index = (int)state;
                        var pData = parallelData[index];

                        records[index] = writeFunction(pData.Enumerate(), pData.ItemsPerTransaction, pData.NumberOfTransactions);

                        countdownEvent.Signal();
                    },
                    i);
            }

            countdownEvent.Wait();
            sw.Stop();

            elapsedMilliseconds = sw.ElapsedMilliseconds;

            return records
                .SelectMany(x => x)
                .ToList();
        }
开发者ID:WimVergouwe,项目名称:ravendb,代码行数:33,代码来源:StoragePerformanceTestBase.cs

示例14: Should_execute_less_than_4_seconds

        public void Should_execute_less_than_4_seconds()
        {
            ThreadPool.SetMinThreads(NumThreads, NumThreads);

            Console.WriteLine("Burst test started");

            _mre.Reset();
            _countdown = new CountdownEvent(NumThreads);

            for (var i = 0; i < NumThreads; i++)
            {
                new Thread(OneThreadExecution) { Name = "Thread " + i }.Start();
            }

            _countdown.Wait();
            var dateTime = DateTime.Now;
            _countdown = new CountdownEvent(NumThreads);
            _mre.Set();
            _countdown.Wait();
            var timeSpan = DateTime.Now - dateTime;

            Console.WriteLine("Test finished");
            Console.WriteLine("Executed at {0}.{1:0}s.", timeSpan.Seconds, timeSpan.Milliseconds / 100);

            if (timeSpan.Seconds > 5)
            {
                Assert.Ignore("This test should't take more than to 4 seconds to run");
            }
        }
开发者ID:joaofx,项目名称:HumbleNetwork,代码行数:29,代码来源:BurstRequestsTest.cs

示例15: RunDisruptorPass

        protected override long RunDisruptorPass()
        {
            Setup();
            var latch = new CountdownEvent(NUM_EVENT_PROCESSORS);
            var listTh = new List<Thread>();
            for (int i = 0; i < 3; i++)
            {
                handlers[i].Reset(latch, -1 + ITERATIONS);
            }

            disruptor.Start();
            var start = System.Diagnostics.Stopwatch.StartNew();

            for (long i = 0; i < ITERATIONS; i++)
            {
                long sequence = ringBuffer.Next();
                ringBuffer[sequence].Value = i;
                ringBuffer.Publish(sequence);
            }
            latch.Wait();
            long opsPerSecond = (ITERATIONS * 1000L) / start.ElapsedMilliseconds;
            for (int i = 0; i < NUM_EVENT_PROCESSORS; i++)
            {
                Assert.AreEqual(results[i], handlers[i].Value);
            }
            disruptor.Shutdown();
            return opsPerSecond;
        }
开发者ID:bingyang001,项目名称:disruptor-net-3.3.0-alpha,代码行数:28,代码来源:OnePublisherToThreeProcessorMultiCastThroughputTest.cs


注:本文中的System.Threading.CountdownEvent.Wait方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。