Example #1
0
        private static void Run()
        {
            using (var countdown = new CountdownEvent(2))
            {
                var subscriber = new Subscriber(MqttBrokerAddress, MqttBrokerPort);
                subscriber.Subscribe(Topic.Hello, Topic.Goodbye);
                subscriber.OnMessage += (topic, payload) =>
                {
                    if (topic == Topic.Hello)
                    {
                        var msg = JsonConvert.DeserializeObject<HelloMessage>(payload);
                        _log.Info("Topic: " + topic);
                        _log.Info("Message: " + msg);
                        countdown.Signal();
                    }
                    else if (topic == Topic.Goodbye)
                    {
                        var msg = JsonConvert.DeserializeObject<GoodbyeMessage>(payload);
                        _log.Info("Topic: " + topic);
                        _log.Info("Message: " + msg);
                        countdown.Signal();
                    }
                };

                var publisher = new Publisher(MqttBrokerAddress, MqttBrokerPort);
                publisher.Publish(Topic.Hello, new HelloMessage() { Name = "John Smith", Date = DateTime.Now });
                publisher.Publish(Topic.Goodbye, new GoodbyeMessage() { Name = "Jane Smith", Date = DateTime.Now });
                countdown.Wait();
            }
        }
Example #2
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);
		}
		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();
		}
        private static void CurrentThreadSchedulerRecursiveSchedulingExample()
        {
            Demo.DisplayHeader("CurrentThreadScheduler - Recursive scheduling will queue the action on caller thread");

            var currentThreadScheduler = CurrentThreadScheduler.Instance;

            var countdownEvent = new CountdownEvent(2);

            currentThreadScheduler.Schedule(Unit.Default,
                (s, _) =>
                {
                    Console.WriteLine("Outer Action - Thread:{0}", Thread.CurrentThread.ManagedThreadId);
                    s.Schedule(Unit.Default,
                        (s2, __) =>
                        {
                            Console.WriteLine("Inner Action - Thread:{0}", Thread.CurrentThread.ManagedThreadId);
                            countdownEvent.Signal();
                            Console.WriteLine("Inner Action - Done:{0}", Thread.CurrentThread.ManagedThreadId);
                            return Disposable.Empty;
                        });
                    countdownEvent.Signal();
                    Console.WriteLine("Outer Action - Done");

                    return Disposable.Empty;
                });

            countdownEvent.Wait();
        }
Example #5
0
        static void Main(string[] args)
        {
            var customers = Enumerable.Range(1, 20);

            using (var countdown = new CountdownEvent(1))
            {
                foreach (var customer in customers)
                {
                    int currentCustomer = customer;

                    countdown.AddCount();
                    ThreadPool.QueueUserWorkItem(delegate
                    {
                        BuySomeStuff(currentCustomer);
                        countdown.Signal();
                    });
                }

                countdown.Signal();
                countdown.Wait();
            }

            Console.WriteLine("All Customers finished shopping...");
            Console.ReadKey();
        }
Example #6
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 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();
     }
 }
Example #8
0
		public void BasicUsageTest ()
		{
			bool act1 = false, act2 = false;
			var evt = new CountdownEvent (2);

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

			block.LinkTo (action1);
			block.LinkTo (action2);

			Assert.IsTrue (block.Post (42), "#1");
			Assert.IsFalse (block.Post (43), "#2");

			Assert.IsTrue (evt.Wait (1000), "#3");

			Assert.IsTrue (act1, "#4");
			Assert.IsTrue (act2, "#5");
		}
Example #9
0
    public void TestGetPointsForRectangle()
    {
      RunAndAwait( () =>
        {
          double startingLat = 10;
          double startingLong = 10;
          int maxPoints = 10;
          SetDefinedCategory( GetRandomCategory() );
          Dictionary<String, String> meta = GetRandomSimpleMetadata();
          CountdownEvent latch = new CountdownEvent( maxPoints );

          for( int i = 0; i < maxPoints; i++ )
          {
            Backendless.Geo.SavePoint( startingLat, startingLong + i, GetDefinedCategories(), meta,
                                       new AsyncCallback<GeoPoint>( response => latch.Signal(), fault =>
                                         {
                                           for( int j = 0; j < latch.CurrentCount; j++ )
                                             latch.Signal();
                                         } ) );
          }
          latch.Wait();

          var geoQuery = new BackendlessGeoQuery( startingLat + 1, startingLong - 1, startingLat - 1,
                                                  startingLong + maxPoints + 1 );
          GetCollectionAndCheck( startingLat, startingLong, maxPoints, maxPoints, meta, geoQuery );
        } );
    }
Example #10
0
        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();
        }
        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();
        }
        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();
        }
Example #13
0
        public void TestGetPointsByMetadata()
        {
            RunAndAwait( () =>
            {
              double startingLat = 20;
              double startingLong = 10;
              int maxPoints = 10;
              SetDefinedCategory( GetRandomCategory() );
              Dictionary<String, String> meta = new Dictionary<string, string>();
              meta.Add( "object_type_sync", "office" );
              CountdownEvent latch = new CountdownEvent( maxPoints );

              for( int i = 0; i < maxPoints; i++ )
              {
            Backendless.Geo.SavePoint( startingLat, startingLong + i, GetDefinedCategories(), meta,
                                       new AsyncCallback<GeoPoint>( response => latch.Signal(), fault =>
                                         {
                                           for( int j = 0; j < latch.CurrentCount; j++ )
                                             latch.Signal();
                                         } ) );
              }
              latch.Wait();

              GetCollectionAndCheck( startingLat, startingLong, maxPoints, maxPoints, meta, new BackendlessGeoQuery(meta) );
            } );
        }
        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");
        }
        public void Should_cosume_multiple_message_types()
        {
            var countdownEvent = new CountdownEvent(3);

            var queue = bus.Advanced.QueueDeclare("multiple_types");

            bus.Advanced.Consume(queue, x => x
                    .Add<MyMessage>((message, info) => 
                        { 
                            Console.WriteLine("Got MyMessage {0}", message.Body.Text);
                            countdownEvent.Signal();
                        })
                    .Add<MyOtherMessage>((message, info) =>
                        {
                            Console.WriteLine("Got MyOtherMessage {0}", message.Body.Text);
                            countdownEvent.Signal();
                        })
                    .Add<IAnimal>((message, info) =>
                        {
                            Console.WriteLine("Got IAnimal of type {0}", message.Body.GetType().Name);
                            countdownEvent.Signal();
                        })
                );

            bus.Advanced.Publish(Exchange.GetDefault(), queue.Name, false, new Message<MyMessage>(new MyMessage { Text = "Hello" }));
            bus.Advanced.Publish(Exchange.GetDefault(), queue.Name, false, new Message<MyOtherMessage>(new MyOtherMessage { Text = "Hi" }));
            bus.Advanced.Publish(Exchange.GetDefault(), queue.Name, false, new Message<Dog>(new Dog()));

            countdownEvent.Wait(1000);
        }
        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");
        }
        public void TestCreate_Running_And_Stop()
        {
            using (var target = new ConsumerWorker<int, int>())
            using (var counter = new CountdownEvent(3))
            using (var completed = new CountdownEvent(1))
            {
                target.Init((k, i) => { counter.Signal(); }, Assert.IsNull);

                var q = new MockQueue {1, 2};
                target.Run(q, w =>
                {
                    Assert.AreSame(w, target);
                    completed.Signal();
                });
                Assert.IsTrue(target.IsRunning);
                Assert.IsTrue(completed.Wait(1000)); //stop is not safe to call before completed (by design)
                target.Stop(w =>
                {
                    Assert.AreSame(w, target);
                    counter.Signal();
                });
                Assert.IsTrue(counter.Wait(1000));
                Assert.IsFalse(target.IsRunning);
            }
        }
        private static SuspendState SuspendImpl(ICollection<ISuspendibleRegisteredObject> allRegisteredObjects) {
            // Our behavior is:
            // - We'll call each registered object's suspend method serially.
            // - All methods have a combined 5 seconds to respond, at which
            //   point we'll forcibly return to our caller.
            // - If a Resume call comes in, we'll not call any Suspend methods
            //   we haven't yet gotten around to, and we'll execute each
            //   resume callback we got.
            // - Resume callbacks may fire in parallel, even if Suspend methods
            //   fire sequentially.
            // - Resume methods fire asynchronously, so other events (such as
            //   Stop or a new Suspend call) could happen while a Resume callback
            //   is in progress.

            CountdownEvent countdownEvent = new CountdownEvent(2);
            SuspendState suspendState = new SuspendState(allRegisteredObjects);

            // Unsafe QUWI since occurs outside the context of a request.
            // We are not concerned about impersonation, identity, etc.

            // Invoke any registered subscribers to let them know that we're about
            // to suspend. This is done in parallel with ASP.NET's own cleanup below.
            if (allRegisteredObjects.Count > 0) {
                ThreadPool.UnsafeQueueUserWorkItem(_ => {
                    suspendState.Suspend();
                    countdownEvent.Signal();
                }, null);
            }
            else {
                countdownEvent.Signal(); // nobody is subscribed
            }

            // Release any unnecessary memory that we're holding on to. The GC will
            // be able to reclaim these, which means that we'll have to page in less
            // memory when the next request comes in.
            ThreadPool.UnsafeQueueUserWorkItem(_ => {
                // Release any char[] buffers we're keeping around
                HttpWriter.ReleaseAllPooledBuffers();

                // Trim expired entries from the runtime cache
                var cache = HttpRuntime.GetCacheInternal(createIfDoesNotExist: false);
                if (cache != null) {
                    cache.TrimCache(0);
                }

                // Trim all pooled HttpApplication instances
                HttpApplicationFactory.TrimApplicationInstances(removeAll: true);

                countdownEvent.Signal();
            }, null);

            if (Debug.IsDebuggerPresent()) {
                countdownEvent.Wait(); // to assist with debugging, don't time out if a debugger is attached
            }
            else {
                countdownEvent.Wait(_suspendMethodTimeout); // blocking call, ok for our needs since has finite wait time
            }
            return suspendState;
        }
        public void Execute()
        {
            //
            // 初期カウントが1のCountdownEventオブジェクトを作成.
            //
            // この場合、どこかの処理にてカウントを一つ減らす必要がある。
            // カウントが残っている状態でWaitをしていると、いつまでたってもWaitを
            // 抜けることが出来ない。
            //
            using (var cde = new CountdownEvent(1))
            {
                // 初期の状態を表示.
                Output.WriteLine("InitialCount={0}", cde.InitialCount);
                Output.WriteLine("CurrentCount={0}", cde.CurrentCount);
                Output.WriteLine("IsSet={0}", cde.IsSet);

                var t = Task.Factory.StartNew(() =>
                                              {
                                                  Thread.Sleep(TimeSpan.FromSeconds(1));

                                                  //
                                                  // カウントをデクリメント.
                                                  //
                                                  // Signalメソッドを引数なしで呼ぶと、1つカウントを減らすことが出来る。
                                                  // (指定した数分、カウントをデクリメントするオーバーロードも存在する。)
                                                  //
                                                  // CountdownEvent.CurrentCountが0の状態で、さらにSignalメソッドを呼び出すと
                                                  // InvalidOperationException (イベントのカウントを 0 より小さい値にデクリメントしようとしました。)が
                                                  // 発生する。
                                                  //
                                                  cde.Signal();
                                                  cde.Signal(); // このタイミングで例外が発生する.
                                              });

                try
                {
                    t.Wait();
                }
                catch (AggregateException aggEx)
                {
                    foreach (var innerEx in aggEx.Flatten().InnerExceptions)
                    {
                        Output.WriteLine("ERROR={0}", innerEx.Message);
                    }
                }

                //
                // カウントが0になるまで待機.
                //
                cde.Wait();

                // 現在の状態を表示.
                Output.WriteLine("InitialCount={0}", cde.InitialCount);
                Output.WriteLine("CurrentCount={0}", cde.CurrentCount);
                Output.WriteLine("IsSet={0}", cde.IsSet);
            }
        }
        static void Main(string[] args)
        {
            var handle = new EventWaitHandle(true, EventResetMode.AutoReset);
            var handle2 = new EventWaitHandle(true, EventResetMode.ManualReset);
            var handle3 = new AutoResetEvent(true);

            CountdownEvent ce = new CountdownEvent(4);

            WaitHandle.WaitAny(new WaitHandle[] { ce.WaitHandle });

            var instance = new SingleThreaded();
            new Thread(() => {

                instance.OneCallInstance1();
                ce.Signal();
            }).Start();

            new Thread(() => {

                lock (instance) {
                    Console.WriteLine("Main");
                    Console.ReadLine();
                    Console.WriteLine("Main");

                }
                ce.Signal();
            }).Start();

            new Thread(() => {

                instance.OneCallInstance2();
                ce.Signal();
            }).Start();

            new Thread(() => {

                instance.OneCallLockThis();
                ce.Signal();
            }).Start();

            //new Thread(() => {

            //    SingleThreaded.OneCallStatic1();
            //}).Start();

            //new Thread(() => {

            //    SingleThreaded.OneCallStatic2();
            //}).Start();

            ce.Wait();
            //Console.ReadLine();
        }
Example #21
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();
            });
        }
Example #22
0
        public void TestCollectionGetPage()
        {
            RunAndAwait( () =>
            {
              var getPageEntities = new List<GetPageEntityAsync>();
              var latch = new CountdownEvent( 20 );
              for( int i = 10; i < 30; i++ )
              {
            var entity = new GetPageEntityAsync {Name = "name#" + i, Age = 20 + i};
            Backendless.Persistence.Save( entity,
                                          new AsyncCallback<GetPageEntityAsync>( response => latch.Signal(), fault =>
                                            {
                                              for( int j = 0; j < latch.CurrentCount; j++ )
                                                latch.Signal();
                                            } ) );

            if( i > 19 && i < 30 )
              getPageEntities.Add( entity );
              }
              latch.Wait();

              var dataQuery = new BackendlessDataQuery( new QueryOptions( 10, 0, "Age" ) );
              Backendless.Persistence.Of<GetPageEntityAsync>()
                     .Find( dataQuery,
                            new ResponseCallback<BackendlessCollection<GetPageEntityAsync>>( this )
                              {
                                ResponseHandler =
                                  response =>
                                  response.GetPage( 10, 10,
                                                    new ResponseCallback<BackendlessCollection<GetPageEntityAsync>>( this )
                                                      {
                                                        ResponseHandler = collection =>
                                                          {
                                                            Assert.IsNotNull( collection, "Next page returned a null object" );
                                                            Assert.IsNotNull( collection.GetCurrentPage(),
                                                                              "Next page contained a wrong data size" );
                                                            Assert.AreEqual( getPageEntities.Count,
                                                                             collection.GetCurrentPage().Count,
                                                                             "Next page returned a wrong size" );

                                                            foreach( GetPageEntityAsync entity in getPageEntities )
                                                              Assert.IsTrue(
                                                                collection.GetCurrentPage().Contains( entity ),
                                                                "Server result didn't contain expected entity" );

                                                            CountDown();
                                                          }
                                                      } )
                              } );
            } );
        }
Example #23
0
        public void DoubleTimeoutedWaitTest()
        {
            var evt = new ManualResetEventSlim();
            var t = new Task(delegate { });
            var cntd = new CountdownEvent(2);

            bool r1 = false, r2 = false;
            ThreadPool.QueueUserWorkItem(delegate { r1 = !t.Wait(100); cntd.Signal(); });
            ThreadPool.QueueUserWorkItem(delegate { r2 = !t.Wait(100); cntd.Signal(); });

            cntd.Wait(2000);
            Assert.IsTrue(r1);
            Assert.IsTrue(r2);
        }
 public void TestScheduling()
 {
     var ch = new EmbeddedChannel(new ChannelHandlerAdapter());
     var latch = new CountdownEvent(2);
     Task future = ch.EventLoop.ScheduleAsync(() => latch.Signal(), TimeSpan.FromSeconds(1));
     future.ContinueWith(t => latch.Signal());
     PreciseTimeSpan next = ch.RunScheduledPendingTasks();
     Assert.True(next > PreciseTimeSpan.Zero);
     // Sleep for the nanoseconds but also give extra 50ms as the clock my not be very precise and so fail the test
     // otherwise.
     Thread.Sleep(next.ToTimeSpan() + TimeSpan.FromMilliseconds(50));
     Assert.Equal(PreciseTimeSpan.MinusOne, ch.RunScheduledPendingTasks());
     latch.Wait();
 }
Example #25
0
		public void UnsafeQueueUserWorkItem_MulticastDelegate ()
		{
			CountdownEvent ev = new CountdownEvent (2);

			e += delegate {
				ev.Signal ();
			};

			e += delegate {
				ev.Signal ();
			};

			ThreadPool.UnsafeQueueUserWorkItem (e, null);
			Assert.IsTrue (ev.Wait (3000));
		}
Example #26
0
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test void awaitingShutdownMustBlockUntilAllMessagesHaveBeenProcessed() throws Exception
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
        internal virtual void AwaitingShutdownMustBlockUntilAllMessagesHaveBeenProcessed()
        {
//JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
//ORIGINAL LINE: final Event specialShutdownObservedEvent = new Event();
            Event specialShutdownObservedEvent = new Event();

//JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
//ORIGINAL LINE: final java.util.concurrent.CountDownLatch awaitStartLatch = new java.util.concurrent.CountDownLatch(1);
            System.Threading.CountdownEvent awaitStartLatch = new System.Threading.CountdownEvent(1);
//JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
//ORIGINAL LINE: final EventConsumer consumer = new EventConsumer();
            EventConsumer consumer = new EventConsumer();
//JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
//ORIGINAL LINE: final AsyncEvents<Event> asyncEvents = new AsyncEvents<>(consumer, AsyncEvents.Monitor_Fields.NONE);
            AsyncEvents <Event> asyncEvents = new AsyncEvents <Event>(consumer, AsyncEvents.Monitor_Fields.None);

            _executor.submit(asyncEvents);

            // Wait for the background thread to start processing events
            do
            {
                asyncEvents.Send(new Event());
            } while (consumer.EventsProcessed.take().processedBy == Thread.CurrentThread);

            // Start a thread that awaits the termination
//JAVA TO C# CONVERTER WARNING: Java wildcard generics have no direct equivalent in .NET:
//ORIGINAL LINE: java.util.concurrent.Future<?> awaitShutdownFuture = executor.submit(() ->
            Future <object> awaitShutdownFuture = _executor.submit(() =>
            {
                awaitStartLatch.Signal();
                asyncEvents.AwaitTermination();
                consumer.EventsProcessed.offer(specialShutdownObservedEvent);
            });

            awaitStartLatch.await();

            // Send 5 events
            asyncEvents.Send(new Event());
            asyncEvents.Send(new Event());
            asyncEvents.Send(new Event());
            asyncEvents.Send(new Event());
            asyncEvents.Send(new Event());

            // Observe 5 events processed
            assertThat(consumer.EventsProcessed.take(), @is(notNullValue()));
            assertThat(consumer.EventsProcessed.take(), @is(notNullValue()));
            assertThat(consumer.EventsProcessed.take(), @is(notNullValue()));
            assertThat(consumer.EventsProcessed.take(), @is(notNullValue()));
            assertThat(consumer.EventsProcessed.take(), @is(notNullValue()));

            // Observe no events left
            assertThat(consumer.EventsProcessed.poll(20, TimeUnit.MILLISECONDS), @is(nullValue()));

            // Shutdown and await termination
            asyncEvents.Shutdown();
            awaitShutdownFuture.get();

            // Observe termination
            assertThat(consumer.EventsProcessed.take(), sameInstance(specialShutdownObservedEvent));
        }
Example #27
0
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test public void shouldHaveTaskQueueSizeEqualToMaxNumberOfProcessors() throws Exception
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
        public virtual void ShouldHaveTaskQueueSizeEqualToMaxNumberOfProcessors()
        {
            // GIVEN
            StageControl control = mock(typeof(StageControl));

//JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
//ORIGINAL LINE: final java.util.concurrent.CountDownLatch latch = new java.util.concurrent.CountDownLatch(1);
            System.Threading.CountdownEvent latch = new System.Threading.CountdownEvent(1);
            const int     processors    = 2;
            int           maxProcessors = 5;
            Configuration configuration = new ConfigurationAnonymousInnerClass(this, maxProcessors);
//JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
//ORIGINAL LINE: final ProcessorStep<Void> step = new BlockingProcessorStep(control, configuration, processors, latch);
            ProcessorStep <Void> step = new BlockingProcessorStep(control, configuration, processors, latch);

            step.Start(ORDER_SEND_DOWNSTREAM);
            step.Processors(1);                 // now at 2
            // adding up to max processors should be fine
            for (int i = 0; i < processors + maxProcessors; i++)
            {
                step.Receive(i, null);
            }

            // WHEN
            Future <Void> receiveFuture = T2.execute(Receive(processors, step));

            T2.get().waitUntilThreadState(Thread.State.TIMED_WAITING);
            latch.Signal();

            // THEN
            receiveFuture.get();
        }
Example #28
0
 public override void Run()
 {
     try
     {
         while (!outerInstance.stop)
         {
             try
             {
                 using (Transaction transaction = Database.beginTx())
                 {
                     Label[]             createdLabels = outerInstance.Labels;
                     Node                node          = Database.createNode(createdLabels);
                     IEnumerable <Label> nodeLabels    = node.Labels;
                     assertEquals(asSet(asList(createdLabels)), asSet(nodeLabels));
                     transaction.Success();
                 }
             }
             catch (Exception e)
             {
                 outerInstance.stop = true;
                 throw e;
             }
         }
     }
     finally
     {
         CreateLatch.Signal();
     }
 }
Example #29
0
 public override void Run()
 {
     Runner = Thread.CurrentThread;
     try
     {
         Pool.acquire();
         OnAcquire.Signal();
         try
         {
             Latch.acquire();
         }
         catch (InterruptedException e)
         {
             throw new Exception(e);
         }
         if (ReleaseConflict.get())
         {
             Pool.release();
             Released.Signal();
         }
     }
     catch (Exception e)
     {
         Console.WriteLine(e.ToString());
         Console.Write(e.StackTrace);
     }
 }
Example #30
0
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test(timeout = 5_000) public void shouldGiveUpAddingMessagesInTheQueueIfTheHandlerHasBeenStopped() throws Throwable
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
        public virtual void ShouldGiveUpAddingMessagesInTheQueueIfTheHandlerHasBeenStopped()
        {
            // given
            BatchingMessageHandler batchHandler = new BatchingMessageHandler(_downstreamHandler, new BoundedPriorityQueue.Config(1, 1, 1024), _batchConfig, _jobSchedulerFactory, NullLogProvider.Instance);

            NewEntry.Request message = new NewEntry.Request(null, new ReplicatedString("dummy"));
            batchHandler.Handle(Wrap(message));                   // fill the queue

            System.Threading.CountdownEvent latch = new System.Threading.CountdownEvent(1);

            // when
            Thread thread = new Thread(() =>
            {
                latch.Signal();
                batchHandler.Handle(Wrap(message));
            });

            thread.Start();

            latch.await();

            batchHandler.Stop();

            thread.Join();

            // then we are not stuck and we terminate
        }
        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
            };
        }
Example #32
0
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test(timeout = 3_000) public void shouldGiveUpQueueingOnStop() throws Throwable
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
        public virtual void ShouldGiveUpQueueingOnStop()
        {
            // given
            for (int i = 1; i <= _maxBatchSize; i++)                 // fell the queue
            {
                _txApplier.queue(CreateTxWithId(_startTxId + i));
            }

            // when
            System.Threading.CountdownEvent latch = new System.Threading.CountdownEvent(1);
            Thread thread = new Thread(() =>
            {
                latch.Signal();
                try
                {
                    _txApplier.queue(CreateTxWithId(_startTxId + _maxBatchSize + 1));
                }
                catch (Exception e)
                {
                    throw new Exception(e);
                }
            });

            thread.Start();

            latch.await();
            _txApplier.stop();

            // then we don't get stuck
            thread.Join();
        }
        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();
        }
        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();
        }
Example #35
0
        public void Should_invoke_delivery_failure_only_when_failing_in_the_same_context()
        {
            var handle = new CountdownEvent(2);

            var first = false;
            var second = false;

            Bus.PublishMandatory(new MyNeverSubscribedToMessage {Value = 1}, reason => { first = true; handle.Signal(); });
            Bus.PublishMandatory(new MyNeverSubscribedToMessage { Value = 2 }, reason => { second = true; handle.Signal(); });

            if(!handle.Wait(100))
                Assert.Fail("Delivery failure callbacks were not called");

            Assert.IsTrue(first);
            Assert.IsTrue(second);
        }
Example #36
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();
            }
Example #37
0
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test void mustNotApplyAsyncWorkInParallelUnderStress() throws Exception
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
        internal virtual void MustNotApplyAsyncWorkInParallelUnderStress()
        {
            int workers        = Runtime.Runtime.availableProcessors() * 5;
            int iterations     = 1_000;
            int incrementValue = 42;

            System.Threading.CountdownEvent startLatch = new System.Threading.CountdownEvent(workers);
            System.Threading.CountdownEvent endLatch   = new System.Threading.CountdownEvent(workers);
            AtomicBoolean   start = new AtomicBoolean();
            Callable <Void> work  = () =>
            {
                startLatch.Signal();
                bool spin;
                do
                {
                    spin = !start.get();
                } while (spin);

                ThreadLocalRandom  rng    = ThreadLocalRandom.current();
                IList <AsyncApply> asyncs = new List <AsyncApply>();
                for (int i = 0; i < iterations; i++)
                {
                    asyncs.add(_sync.applyAsync(new AddWork(incrementValue)));
                    if (rng.Next(10) == 0)
                    {
                        foreach (AsyncApply async in asyncs)
                        {
                            async.Await();
                        }
                        asyncs.clear();
                    }
                }

                foreach (AsyncApply async in asyncs)
                {
                    async.Await();
                }
                endLatch.Signal();
                return(null);
            };

            IList <Future <Void> > futureList = new List <Future <Void> >();

            for (int i = 0; i < workers; i++)
            {
                futureList.Add(_executor.submit(work));
            }
            startLatch.await();
            start.set(true);
            endLatch.await();

            foreach (Future <Void> future in futureList)
            {
                future.get();                         // check for any exceptions
            }

            assertThat(_count.sum(), lessThan((long)(workers * iterations)));
            assertThat(_sum.sum(), @is((long)(incrementValue * workers * iterations)));
        }
Example #38
0
//JAVA TO C# CONVERTER WARNING: 'final' parameters are ignored unless the option to convert to C# 7.2 'in' parameters is selected:
//ORIGINAL LINE: private Runnable createReader(final RWLock lock, final LockTransaction transaction, final java.util.concurrent.CountDownLatch latch)
        private ThreadStart CreateReader(RWLock @lock, LockTransaction transaction, System.Threading.CountdownEvent latch)
        {
            return(() =>
            {
                @lock.Mark();
                @lock.AcquireReadLock(LockTracer.NONE, transaction);
                latch.Signal();
            });
        }
Example #39
0
//JAVA TO C# CONVERTER WARNING: 'final' parameters are ignored unless the option to convert to C# 7.2 'in' parameters is selected:
//ORIGINAL LINE: private Runnable createFailedWriter(final RWLock lock, final LockTransaction transaction, final java.util.concurrent.CountDownLatch latch)
        private ThreadStart CreateFailedWriter(RWLock @lock, LockTransaction transaction, System.Threading.CountdownEvent latch)
        {
            return(() =>
            {
                @lock.Mark();
                assertFalse(@lock.AcquireWriteLock(LockTracer.NONE, transaction));
                latch.Signal();
            });
        }
Example #40
0
 private OtherThreadExecutor.WorkerCommand <object, object> WriteToFirstAndSecond()
 {
     return(state =>
     {
         HTTP.Response post = _http.POST("db/data/transaction", quotedJson("{ 'statements': [ { 'statement': 'MATCH (n:Second) SET n.prop=1' } ] }"));
         _secondNodeLocked.Signal();
         _http.POST(post.location(), quotedJson("{ 'statements': [ { 'statement': 'MATCH (n:First) SET n.prop=1' } ] }"));
         return null;
     });
 }
Example #41
0
 public override void Reached()
 {
     try
     {
         ReachedConflict.Signal();
         Released.await();
     }
     catch (InterruptedException e)
     {
         throw new Exception(e);
     }
 }
 public override void Panic(Exception cause)
 {
     PanicLatch.Signal();
     try
     {
         AdversaryLatch.await();
     }
     catch (InterruptedException e)
     {
         throw new Exception(e);
     }
     base.Panic(cause);
 }
Example #43
0
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test(timeout = 5_000) public void shouldWaitForAllJobsToFinish() throws Throwable
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
        public virtual void ShouldWaitForAllJobsToFinish()
        {
            // Given
            when(_config.jobLimit()).thenReturn(2);

            JobScheduler jobScheduler = createInitialisedScheduler();

//JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
//ORIGINAL LINE: final IndexSamplingJobTracker jobTracker = new IndexSamplingJobTracker(config, jobScheduler);
            IndexSamplingJobTracker jobTracker = new IndexSamplingJobTracker(_config, jobScheduler);

//JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
//ORIGINAL LINE: final java.util.concurrent.CountDownLatch latch1 = new java.util.concurrent.CountDownLatch(1);
            System.Threading.CountdownEvent latch1 = new System.Threading.CountdownEvent(1);
//JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
//ORIGINAL LINE: final java.util.concurrent.CountDownLatch latch2 = new java.util.concurrent.CountDownLatch(1);
            System.Threading.CountdownEvent latch2 = new System.Threading.CountdownEvent(1);

            WaitingIndexSamplingJob job1 = new WaitingIndexSamplingJob(IndexId11, latch1);
            WaitingIndexSamplingJob job2 = new WaitingIndexSamplingJob(IndexId22, latch1);

            jobTracker.ScheduleSamplingJob(job1);
            jobTracker.ScheduleSamplingJob(job2);

//JAVA TO C# CONVERTER WARNING: Java wildcard generics have no direct equivalent in .NET:
//ORIGINAL LINE: java.util.concurrent.Future<?> stopping = java.util.concurrent.Executors.newSingleThreadExecutor().submit(() ->
            Future <object> stopping = Executors.newSingleThreadExecutor().submit(() =>
            {
                latch2.Signal();
                try
                {
                    jobTracker.AwaitAllJobs(10, TimeUnit.SECONDS);
                }
                catch (InterruptedException e)
                {
                    throw new Exception(e);
                }
            });

            // When
            latch2.await();
            assertFalse(stopping.Done);
            latch1.Signal();
            stopping.get(10, SECONDS);

            // Then
            assertTrue(stopping.Done);
            assertNull(stopping.get());
            assertTrue(job1.Executed);
            assertTrue(job2.Executed);
        }