Wait() 개인적인 메소드

private Wait ( Func waitPredicate ) : bool
waitPredicate Func
리턴 bool
        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));
            }
        }
 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();
     }
 }
        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();
        }
        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");
        }
예제 #5
0
        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();
            });
        }
        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();
        }
예제 #7
0
        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);
        }
예제 #8
0
파일: Program.cs 프로젝트: TBXin/dotnetex
        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();
        }
        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;
        }
예제 #10
0
        private async Task RunDemo(string url)
        {
            cde = new CountdownEvent(invocations);
            ITaskAgent client = this;
            ITaskScheduler server = this;

            var hubConnection = new HubConnection(url);
            hubConnection.TraceWriter = _traceWriter;

            _hubProxy = hubConnection.CreateHubProxy("TaskSchedulerHub");            
            _hubProxy.On<TimeSpan>("RunSync", client.RunSync);
            _hubProxy.On<TimeSpan>("RunAsync", (data) => client.RunAsync(data));

            await hubConnection.Start(new LongPollingTransport());

            var smallDuration = TimeSpan.FromMilliseconds(500);
            var largeDuration = TimeSpan.FromSeconds(10);

            for (int i = 0; i < invocations; i++ )
            {
                server.AssignMeShortRunningTask(smallDuration);
                server.AssignMeLongRunningTask(largeDuration);
            }

            cde.Wait();
        }
예제 #11
0
		public void Network_partition_should_cause_message_resend()
		{
			var leader = CreateNetworkAndGetLeader(3, messageTimeout: 300);
			
			var countdown = new CountdownEvent(2);
			leader.ElectionStarted += () =>
			{
				if (countdown.CurrentCount > 0)
					countdown.Signal();
			};
			WriteLine("Disconnecting network");
			for (int i = 0; i < 3; i++)
			{
				DisconnectNode("node" + i);
				DisconnectNodeSending("node" + i);
			}

			for (int i = 0; i < 5; i++)
			{
				ForceTimeout(leader.Name);

			}
			Assert.True(countdown.Wait(1500));

			for (int i = 0; i < 3; i++)
			{
				ReconnectNode("node" + i);
				ReconnectNodeSending("node" + i);
			}

			Assert.True(Nodes.First().WaitForLeader());
		}
        public 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 map = client.GetMap<string, string>("listener-example");

            var cdown = new CountdownEvent(2);
            map.AddEntryListener(new EntryAdapter<string, string>
            {
                Added = e =>
                {
                    Console.WriteLine("Key '{0}' with value ' {1}' was added.", e.GetKey(), e.GetValue());
                    cdown.Signal();
                },
                Removed = e =>
                {
                    Console.WriteLine("Key '{0}' with value ' {1}' was removed.", e.GetKey(), e.GetOldValue());
                    cdown.Signal();
                }
            }, true);

            map.Put("key", "value");
            map.Remove("key");

            cdown.Wait();
            map.Destroy();
        }
        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");
        }
예제 #14
0
        public void QueueUserWorkItemShouldProcessSimultaneousRequestsSequentially()
        {
            // Arrange
            const int expected = NUM_THREADS * LOOP_COUNT;
            var countdownEvent = new CountdownEvent(expected);
            ITaskScheduler singleThreadedTaskScheduler = new Core.Impl.SequentialTaskScheduler(null);
            Helper volatileFieldHelper = new Helper();

            // Act
            for (int i = 0; i < NUM_THREADS; i++)
            {
                new Thread(() =>
                {
                    for (int j = 0; j < LOOP_COUNT; j++)
                    {
                        singleThreadedTaskScheduler.ScheduleTask(() =>
                        {
                            int initialCount = volatileFieldHelper.Field;
                            Thread.Yield();
                            volatileFieldHelper.Field = initialCount + 1;
                            countdownEvent.Signal();
                        });
                    }
                }).Start();
            }

            // Assert
            Assert.IsTrue(countdownEvent.Wait(TimeSpan.FromSeconds(5)), "CountdownEvent timed out waiting to be signaled.");
            Assert.AreEqual(expected, volatileFieldHelper.Field, "Wrong count - race condition?");
        }
        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();
        }
예제 #16
0
        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");
        }
예제 #17
0
		public void BasicUsageTest ()
		{
			bool act1 = false, act2 = false;
			var evt = new CountdownEvent (2);

			var broadcast = new BroadcastBlock<int> (null);
			var action1 = new ActionBlock<int> (i =>
			{
				act1 = i == 42;
				evt.Signal ();
			});
			var action2 = new ActionBlock<int> (i =>
			{
				act2 = i == 42;
				evt.Signal ();
			});

			broadcast.LinkTo (action1);
			broadcast.LinkTo (action2);

			Assert.IsTrue (broadcast.Post (42));

			Assert.IsTrue (evt.Wait (100));

			Assert.IsTrue (act1);
			Assert.IsTrue (act2);
		}
예제 #18
0
		public void Test()
		{
			var CustomThreadPool = new CustomThreadPool(2);
			var Results0 = new List<int>();
			var Results1 = new List<int>();
			var CountdownEvent = new CountdownEvent(2);

			CustomThreadPool.AddTask(0, () =>
			{
				Thread.Sleep(10);
				Results0.Add(0);
			});
			CustomThreadPool.AddTask(0, () =>
			{
				Results0.Add(1);
				CountdownEvent.Signal();
			});
			CustomThreadPool.AddTask(1, () =>
			{
				Results1.Add(0);
				CountdownEvent.Signal();
			});

			CountdownEvent.Wait();
			Thread.Sleep(10);
			Assert.IsTrue(CustomThreadPool.GetLoopIterCount(0) <= 2);
			Assert.IsTrue(CustomThreadPool.GetLoopIterCount(1) <= 2);
			Assert.AreEqual("0,1", Results0.ToStringArray());
			Assert.AreEqual("0", Results1.ToStringArray());
			CustomThreadPool.Stop();
		}
        public void ProperRooting_NoGC_SingleShot()
        {
            var cts = new CancellationTokenSource();

            new Thread(() =>
            {
                while (!cts.IsCancellationRequested)
                {
                    Thread.Sleep(50);
                    GC.Collect();
                    GC.WaitForPendingFinalizers();
                }
            }).Start();

            var tp = ThreadPoolScheduler.Instance;
            var N = 100;
            var cd = new CountdownEvent(N);
            for (int i = 0; i < N; i++)
            {
                tp.Schedule(TimeSpan.FromMilliseconds(100 + i), () => { cd.Signal(); });
            }

            Assert.True(cd.Wait(TimeSpan.FromMinutes(1)));
            cts.Cancel();
        }
예제 #20
0
        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;
        }
예제 #21
0
        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 )
                       } );
            } );
        }
        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();
        }
예제 #23
0
            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();
            }
예제 #24
0
        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");
            }
        }
예제 #25
0
        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();
        }
        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
            };
        }
예제 #27
0
        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));
        }
예제 #28
0
        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();
        }
        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;
        }
		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");
		}
예제 #31
0
        static void Main(string[] args)
        {
            //// system io test
            ////  - start a process , redirect output to a memory stream and then run the cmd and send that output to standard out
            //ProcessStartInfo cmd = new ProcessStartInfo("cmd.exe");
            //cmd.RedirectStandardInput = true;
            //cmd.RedirectStandardOutput = true;
            //cmd.UseShellExecute = false;
            //cmd.CreateNoWindow = false;
            //cmd.WindowStyle = ProcessWindowStyle.Normal;

            //Process console = Process.Start(cmd);
            //commandOutputStream = console.StandardOutput;
            //console.StandardInput.WriteLine(command);
            //console.StandardInput.WriteLine("EXIT");
            //console.WaitForExit();



            // uncomment the test to run - OK - I may only end up running one type ;)

            //// Test - simple run a command + simple queuing
            //var myCommands = new command();
            //System.Console.Out.WriteLine("START");
            //System.Console.Out.WriteLine("queue 1");
            //System.Threading.ThreadPool.QueueUserWorkItem (new System.Threading.WaitCallback(myCommands.thread1Command));
            //System.Console.Out.WriteLine("queue 2");
            // System.Threading.ThreadPool.QueueUserWorkItem(new System.Threading.WaitCallback(myCommands.thread2Command));
            //System.Console.Out.WriteLine("END");

            // test - multi-queue - used to learn how to wait for the end of tasks & to test general performance
            //  use the countdownevent pattern
            var myCommands = new command();

            //var state = new object();
            System.Console.Out.WriteLine("START");
            var cde = new System.Threading.CountdownEvent(1);

            for (var i = 1; i <= 100; i++)
            {
                System.Console.Out.WriteLine("queue " + i);
                System.Threading.ThreadPool.QueueUserWorkItem(new System.Threading.WaitCallback(myCommands.bogusTask), cde);
                // increment the counter
                cde.AddCount(1);
            }
            // decrement the counter - we started with one !
            //  - prevents the race condition where tasks finish before queueing is done !
            cde.Signal();
            // wait for all tasks to be complete -  the final (0) countdown event
            cde.Wait();
            System.Console.Out.WriteLine("END");
        }
        static void Main(string[] args)
        {
            for (int i = 0; i < taskCount; i++)
            {
                Task.Factory.StartNew(() =>
                {
                    Console.WriteLine($"Entering Task {Task.CurrentId}");
                    Thread.Sleep(random.Next(3000));
                    cde.Signal();
                    Console.WriteLine($"Exit Task {Task.CurrentId}");
                });
            }

            Task task = Task.Factory.StartNew(() =>
            {
                Console.WriteLine($"Waiting in final task id {Task.CurrentId} for countdown to end");
                cde.Wait();
                Console.WriteLine("Finished with final task");
            });

            task.Wait();
        }
예제 #33
0
        private static void Main(string[] args)
        {
            foreach (var i in Enumerable.Range(1, 5))
            {
                Task.Factory.StartNew(() =>
                {
                    Console.WriteLine($"Starting Task {Task.CurrentId}...");
                    Thread.Sleep(Random.Next(10000));
                    Countdown.Signal();
                    Console.WriteLine($" - Completed Task {Task.CurrentId}.");
                });
            }

            var task = Task.Factory.StartNew(() =>
            {
                Console.WriteLine($"Waiting for other tasks to complete, TaskId = {Task.CurrentId}");
                Countdown.Wait();
                Console.WriteLine("All tasks are done with their execution");
            });

            task.Wait();

            Console.ReadLine();
        }
예제 #34
0
        static async Task Main(string[] args)
        {
            // Initialize a queue and a CountdownEvent
            ConcurrentQueue <int> queue = new ConcurrentQueue <int>(Enumerable.Range(0, 10000));

            System.Threading.CountdownEvent cde = new System.Threading.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();

            Console.ReadLine();
        }
예제 #35
0
파일: Program.cs 프로젝트: evisar/lambda
        static void Main(string[] args)
        {
            var dirs = Directory.GetDirectories("c:\\lambda\\cluster\\");

            Console.WriteLine("Running Lambda Cluster with {0} nodes", dirs.Length);

            var iw = new FileSystemWatcher("c:\\lambda\\sessions\\", "*.exe");

            iw.Created += (sender, e) =>
            {
                Task.Run(() =>
                {
                    bool failed = true;
                    while (failed)
                    {
                        try
                        {
                            using (File.OpenRead(e.FullPath)) { }
                            failed = false;
                        }
                        catch
                        {
                            Task.Delay(333);
                        }
                    }


                    var fi = new FileInfo(e.FullPath);

                    var countdown = new System.Threading.CountdownEvent(dirs.Length);
                    var session   = Guid.NewGuid().ToString();
                    Console.WriteLine("Session: {0}", session);
                    Console.WriteLine("Timestamp:{0}", DateTime.Now);
                    Console.WriteLine("Process:{0}", e.FullPath);
                    var sw   = Stopwatch.StartNew();
                    var di   = Directory.CreateDirectory("c:\\lambda\\sessions\\" + session);
                    var pid  = new List <int>();
                    var path = e.FullPath;
                    foreach (var dir in dirs)
                    {
                        Process p = Run(path, dir, di.FullName);
                        pid.Add(p.Id);
                        p.EnableRaisingEvents = true;
                        p.Exited += (x, y) => countdown.Signal();
                    }
                    Console.WriteLine("Tasks: {0}", string.Join(",", pid.ToArray()));
                    countdown.Wait();

                    var waiter             = new CountdownEvent(1);
                    var pr                 = Run(path, di.FullName, di.FullName, "1");
                    pr.EnableRaisingEvents = true;
                    pr.Exited             += (x, y) => waiter.Signal();
                    sw.Stop();
                    Console.WriteLine("Elapsed: {0}", sw.Elapsed);
                    Console.WriteLine("------------------------------------------");
                    waiter.Wait();

                    File.Delete(e.FullPath);
                });
            };
            iw.EnableRaisingEvents = true;
            Console.ReadLine();
        }