• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

C# Threading.CountdownEvent类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

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



CountdownEvent类属于System.Threading命名空间,在下文中一共展示了CountdownEvent类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的C#代码示例。

示例1: 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


示例2: ConcurrentRunner

 public ConcurrentRunner(int maxThread, int loopEach)
 {
     this.maxThread = maxThread;
     this.loopEach = loopEach;
     this.semaphore = new SemaphoreSlim(0, maxThread);
     this.countdown = new CountdownEvent(maxThread);
 }
开发者ID:sdgdsffdsfff,项目名称:hermes.net,代码行数:7,代码来源:ConcurrentRunner.cs


示例3: 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


示例4: MainWindow

        public MainWindow()
        {
            InitializeComponent();
            Thread.CurrentThread.Name = "Main Thread";

            CountdownEvent folderEndByXML = new CountdownEvent(1);
            CountdownEvent folderEndByTree = new CountdownEvent(1);
            CountdownEvent fileEndByXML = new CountdownEvent(1);
            CountdownEvent fileEndByTree = new CountdownEvent(1);

            m_parser = new Parser(m_progressToken, folderEndByTree, folderEndByXML, fileEndByTree, fileEndByXML);
            m_treeFiller = new TreeFiller(m_treeView, m_progressToken, folderEndByTree, fileEndByTree);
            m_xmlFiller = new XMLFiller(m_progressToken, folderEndByXML, fileEndByXML);

            m_folderName.DataContext = m_parser;
            m_xmlFileName.DataContext = m_xmlFiller;

            m_parser.ItemGrabbed += m_xmlFiller.ItemGrabbedHandler;
            m_parser.ItemGrabbed += m_treeFiller.ItemGrabbedHandler;
            m_parser.FolderStarted += m_xmlFiller.FolderStartedHandler;
            m_parser.FolderStarted += m_treeFiller.FolderStartedHandler;
            m_parser.FolderFinished += m_xmlFiller.FolderFinishedHandler;
            m_parser.FolderFinished += m_treeFiller.FolderFinishedHandler;

            m_parser.ParserFinishEvent += this.ParserFinishEventHandler;

            m_xmlFiller.ExceptionOccuredEvent += this.ExceptionOccuredHandler;
            m_treeFiller.ExceptionOccuredEvent += this.ExceptionOccuredHandler;
            m_parser.ExceptionOccuredEvent += this.ExceptionOccuredHandler;
        }
开发者ID:ILya-Lev,项目名称:FilesPicker,代码行数:30,代码来源:MainWindow.xaml.cs


示例5: Start

        public IDisposable Start()
        {
            _monitor.Start();
            CountdownEvent pending = new CountdownEvent(_args.ConnectionLimit);
            var interval = Observable.Interval(TimeSpan.FromSeconds(1))
                .TakeWhile(_ => pending.CurrentCount > 0)
                .Subscribe(async _ =>
                {
                    var parallelCount = Math.Min(pending.CurrentCount, 10);

                    Task[] tasks = new Task[parallelCount];
                    for (int i = 0; i < parallelCount; i++)
                    {
                        tasks[i] = Task.Run(() => Connect(pending));
                    }

                    Task.WaitAll(tasks);
                },
                ex =>
                {
                    Console.WriteLine(ex.Message);
                    Environment.Exit(1);
                });

            pending.Wait();

            Observable.Interval(TimeSpan.FromSeconds(1)).Subscribe(this.SendMessage);

            return null;
        }
开发者ID:headinthebox,项目名称:IoFx,代码行数:30,代码来源:SocketClientWithAck.cs


示例6: should_reconnect_within_5_seconds

            public void should_reconnect_within_5_seconds()
            {
                const int total = 100;
                var countdown = new CountdownEvent(total);

                IBus producer = this.StartBus("producer", cfg => cfg.Route("boo"));

                IBus consumer = this.StartBus(
                    "consumer",
                    cfg => cfg.On<BooMessage>("boo").
                               ReactWith(
                                   (m, ctx) =>
                                       {
                                           Console.WriteLine("Received {0}.", m.Num);
                                           countdown.Signal();
                                       }));

                int count = total;
                while (count -- > 0)
                {
                    producer.Emit("boo", new BooMessage(count));
                    Console.WriteLine("Sent {0}.", count);
                    Thread.Sleep(1.Seconds());
                }

                countdown.Wait();
            }
开发者ID:ehramovich,项目名称:Contour,代码行数:27,代码来源:ManualSpecs.cs


示例7: Constructor_Zero

		public void Constructor_Zero ()
		{
			var ce = new CountdownEvent (0);
			Assert.IsTrue (ce.IsSet, "#1");
			Assert.AreEqual (0, ce.InitialCount, "#2");
			Assert.IsTrue (ce.Wait (0), "#3");
		}
开发者ID:tupunco,项目名称:Tup.MonoConcurrent,代码行数:7,代码来源:CountdownEventTests.cs


示例8: RunDisruptorPass

        protected override long RunDisruptorPass()
        {
            CountdownEvent latch = new CountdownEvent(1);
            long expectedCount = batchEventProcessor.Sequence.Value + ITERATIONS;
            handler.Reset(latch, ITERATIONS);
            Task.Factory.StartNew(() => batchEventProcessor.Run());
            Stopwatch start = Stopwatch.StartNew();

            RingBuffer<long[]> rb = ringBuffer;

            for (long i = 0; i < ITERATIONS; i++)
            {
                long next = rb.Next();
                long[] @event = rb.Get(next);
                for (int j = 0; j < @event.Length; j++)
                {
                    @event[j] = i;
                }
                rb.Publish(next);
            }

            latch.Wait();
            long opsPerSecond = (ITERATIONS * ARRAY_SIZE * 1000L) / (start.ElapsedMilliseconds);
            waitForEventProcessorSequence(expectedCount);
            batchEventProcessor.Halt();

            PerfTestUtil.failIf(0, handler.Value);

            return opsPerSecond;
        }
开发者ID:bingyang001,项目名称:disruptor-net-3.3.0-alpha,代码行数:30,代码来源:OneToOneSequencedLongArrayThroughputTest.cs


示例9: Should_be_able_to_subscribe_as_exlusive

        public void Should_be_able_to_subscribe_as_exlusive()
        {
            var countdownEvent = new CountdownEvent(10);
            var firstCount = 0;
            var secondCount = 0;

            bus.Subscribe<MyMessage>("test", message =>
                {
                    countdownEvent.Signal();
                    Interlocked.Increment(ref firstCount);
                    Console.WriteLine("[1] " + message.Text);
                }, x => x.AsExclusive());
            bus.Subscribe<MyMessage>("test", message =>
                {
                    countdownEvent.Signal();
                    Interlocked.Increment(ref secondCount);
                    Console.WriteLine("[2] " + message.Text);
                }, x => x.AsExclusive());

            for (var i = 0; i < 10; ++i)
                bus.Publish(new MyMessage
                    {
                        Text = "Exclusive " + i
                    });
            countdownEvent.Wait(10 * 1000);
            Assert.IsTrue(firstCount == 10 && secondCount == 0 || firstCount == 0 && secondCount == 10);
            Console.WriteLine("Stopped consuming");
        }
开发者ID:yonglehou,项目名称:EasyNetQ,代码行数:28,代码来源:PublishSubscribeTests.cs


示例10: TestTimerStartAutoReset

        public void TestTimerStartAutoReset()
        {
            CountdownEvent cde = new CountdownEvent(1);
            int result = 0;
            _timer = new TestTimer(1);

            // Test defaults.
            Assert.Equal(1, _timer.Interval);
            Assert.True(_timer.AutoReset);

            _timer.AutoReset = false;
            _timer.Elapsed += (sender, e) => { result = ++result; cde.Signal(); };
            _timer.Start();

            Assert.True(_timer.Enabled);
            cde.Wait();

            // Only elapsed once.
            Assert.Equal(1, result);

            cde = new CountdownEvent(10);
            _timer.AutoReset = true;

            cde.Wait();
            cde.Dispose();

            _timer.Stop();
            // Atleast elapsed 10 times.
            Assert.True(result >= 10);
        }
开发者ID:omariom,项目名称:corefx,代码行数:30,代码来源:TimerTests.cs


示例11: Run

        private static void Run(string[] args)
        {
            Environment.SetEnvironmentVariable("hazelcast.logging.level", "info");
            Environment.SetEnvironmentVariable("hazelcast.logging.type", "console");

            var config = new ClientConfig();
            config.GetNetworkConfig().AddAddress("127.0.0.1");
            var client = HazelcastClient.NewHazelcastClient(config);

            var list = client.GetList<string>("collection-listener-example");
            var cdown = new CountdownEvent(3);
            list.AddItemListener(new ItemListener<string>
            {
                OnItemAdded = e =>
                {
                    Console.WriteLine("Item added: " + e.GetItem());
                    cdown.Signal();
                },
                OnItemRemoved = e =>
                {
                    Console.WriteLine("Item removed: " + e.GetItem());
                    cdown.Signal();
                }
            }, true);

            list.Add("item1");
            list.Add("item2");
            list.Remove("item1");

            cdown.Wait();
            list.Destroy();
            client.Shutdown();
        }
开发者ID:ihsandemir,项目名称:hazelcast-csharp-client,代码行数:33,代码来源:CollectionListenerExample.cs


示例12: M1

        static void M1()
        {
            var sameLocalVariable = 123;
            var cdevent = new CountdownEvent(2);

            if (Fork.CloneThread())
            {
                lock (_sync)
                {
                    Console.ReadKey();
                    Console.WriteLine("in forked thread: {0}, tid: {1} ", sameLocalVariable, Thread.CurrentThread.ManagedThreadId);
                    cdevent.Signal();
                }
            }
            else
            {
                lock (_sync)
                {
                    Console.ReadKey();
                    Console.WriteLine("in parent thread: {0}, tid: {1} ", sameLocalVariable, Thread.CurrentThread.ManagedThreadId);
                    cdevent.Signal();
                }
            }

            cdevent.Wait();
        }
开发者ID:TBXin,项目名称:dotnetex,代码行数:26,代码来源:Program.cs


示例13: be_able_to_subscribe_to_non_existing_stream_and_then_catch_event

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

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

                store.AppendToStreamAsync(stream, ExpectedVersion.EmptyStream, TestEvent.NewTestEvent()).Wait();

                if (!appeared.Wait(Timeout))
                {
                    Assert.IsFalse(dropped.Wait(0), "Subscription was dropped prematurely.");
                    Assert.Fail("Appeared countdown event timed out.");
                }

                Assert.IsFalse(dropped.Wait(0));
                subscription.Stop(Timeout);
                Assert.IsTrue(dropped.Wait(Timeout));
            }
        }
开发者ID:czcz1024,项目名称:EventStore,代码行数:29,代码来源:subscribe_to_stream_catching_up_should.cs


示例14: 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


示例15: 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


示例16: 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


示例17: Main

        static void Main(string[] args)
        {
            // initialize the semaphores
            semA = new SemaphoreSlim(2);
            semB = new SemaphoreSlim(2);

            // define the number of tasks we will use
            int taskCount = 10;

            // initialize the barrier
            cdEvent = new CountdownEvent(taskCount);

            Task[] tasks = new Task[10];
            for (int i = 0; i < taskCount; i++) {
                tasks[i] = Task.Factory.StartNew((stateObject) => {
                    InitialMethod((int)stateObject);
                    Console.WriteLine("Task {0} completed", Task.CurrentId);
                }, i);
            }

            // wait for all of the tasks to have reached a terminal method
            cdEvent.Wait();

            // throw an exception to force the debugger to break
            throw new Exception();
        }
开发者ID:clp-takekawa,项目名称:codes-from-books,代码行数:26,代码来源:Listing_04.cs


示例18: Should_catch_EndOfStreamException

        public void Should_catch_EndOfStreamException()
        {
            // Arrange
            var count = new CountdownEvent(2);
            var channel = Substitute.For<IModel>();
            var watcher = Substitute.For<IRabbitWatcher>();
            var queue = Substitute.For<IInMemoryPriorityQueue<GenericPriorityMessage<BasicDeliverEventArgs>>>();
            queue.When(x => x.Dequeue()).Do(callInfo => {
                count.Signal();
                throw new EndOfStreamException();                
            });
            var consumer = new PriorityBurrowConsumer(channel, Substitute.For<IMessageHandler>(), watcher, true, 2);

            var sub = Substitute.For<CompositeSubscription>();
            sub.AddSubscription(new Subscription(channel) { ConsumerTag = "Burrow" });
            consumer.Init(queue, sub, 1, Guid.NewGuid().ToString());
            

            // Action
            consumer.Ready();
            count.Wait();

            // Assert
            consumer.Dispose();
        }
开发者ID:joefeser,项目名称:Burrow.NET,代码行数:25,代码来源:MethodReady.cs


示例19: 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


示例20: SocketConnect

        public void SocketConnect()
        {
            const int port = 5050;
            const int clientCount = 10;
            var listener = SocketEvents.GetTcpStreamSockets(port);
            var countdown = new CountdownEvent(clientCount);
            try
            {
                var tcs = new TaskCompletionSource<object>();
                int count = 0;
                listener.Subscribe(s =>
                {
                    count++;
                    countdown.Signal();
                    s.Close();
                },
                tcs.SetException,
                () => tcs.TrySetResult(null));

                for (int i = 0; i < clientCount; i++)
                {
                    SocketTestUtility.Connect(port);
                }

                countdown.WaitEx();
                Assert.IsTrue(count == clientCount);
            }
            finally
            {
                listener.Dispose();
            }
        }
开发者ID:headinthebox,项目名称:IoFx,代码行数:32,代码来源:SocketAcceptTest.cs



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


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
C# Threading.EventWaitHandle类代码示例发布时间:2022-05-26
下一篇:
C# Threading.CompressedStack类代码示例发布时间:2022-05-26
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap