public void Error(bool systemError)
        {
            Type expected;

            if (systemError)
            {
                expected = typeof(Exception);
                SimpleImpl.throwSystemError = true;
            }
            else
            {
                expected = typeof(TestError);
                SimpleImpl.throwSystemError = false;
            }

            // Test synchronous RPC:
            try
            {
                simpleClient.error();
                Assert.Fail("Expected " + expected.Name + " to be thrown");
            }
            catch (Exception e)
            {
                Assert.AreEqual(expected, e.GetType());
            }

            // Test asynchronous RPC (future):
            var future = new CallFuture <object>();

            simpleClient.error(future);
            try
            {
                future.WaitForResult(2000);
                Assert.Fail("Expected " + expected.Name + " to be thrown");
            }
            catch (Exception e)
            {
                Assert.AreEqual(expected, e.GetType());
            }

            Assert.IsNotNull(future.Error);
            Assert.AreEqual(expected, future.Error.GetType());
            Assert.IsNull(future.Result);

            // Test asynchronous RPC (callback):
            Exception errorRef = null;
            var       latch    = new CountdownLatch(1);

            simpleClient.error(new CallbackCallFuture <object>(
                                   result => Assert.Fail("Expected " + expected.Name),
                                   exception =>
            {
                errorRef = exception;
                latch.Signal();
            }));

            Assert.IsTrue(latch.Wait(2000), "Timed out waiting for error");
            Assert.IsNotNull(errorRef);
            Assert.AreEqual(expected, errorRef.GetType());
        }
Ejemplo n.º 2
0
        public void WaitForEventWithTimeout()
        {
            CountdownLatch countdown = new CountdownLatch(5);
            bool           result    = countdown.WaitOne(TimeSpan.FromMilliseconds(5));

            Assert.IsFalse(result);
        }
Ejemplo n.º 3
0
 public void WaitForConsumersDoesNotWaitIfConsumersAreZero() {
     TestTool.RunTasks(ThreadCount,
                       () => {
                           var result = new CountdownLatch(0).WaitOne();
                           Assert.IsTrue(result);
                       });
 }
Ejemplo n.º 4
0
        bool RunTest <T>(int channelCount, int seedCount, Future <int> complete, Func <T> valueProvider)
        {
            var channels = new Channel <T> [channelCount];

            var latch = new CountdownLatch(channelCount * seedCount, complete.Complete);

            FiberFactory fiberFactory = () => new PoolFiber();

            for (int i = 0; i < channelCount; i++)
            {
                int channelNumber = i;
                channels[i] = new ConsumerChannel <T>(fiberFactory(), x =>
                {
                    if (channelNumber < channels.Length - 1)
                    {
                        channels[channelNumber + 1].Send(x);
                    }

                    latch.CountDown();
                });
            }

            for (int i = 0; i < seedCount; i++)
            {
                channels[i].Send(valueProvider());

                for (int j = 0; j < i; j++)
                {
                    latch.CountDown();
                }
            }

            return(complete.WaitUntilCompleted(24.Seconds()));
        }
Ejemplo n.º 5
0
        public void Consistently_updated_by_multiple_threads()
        {
            const int itemCount = 10;
            var       items     = new int[itemCount];

            for (var i = 0; i < itemCount; i++)
            {
                items[i] = i;
            }

            var itemsRef = Ref.Of(items.ToArray());

            const int threadCount = 10;
            var       latch       = new CountdownLatch(threadCount);

            for (var i = threadCount - 1; i >= 0; i--)
            {
                var delay  = i * 10;
                var thread = new Thread(() =>
                {
                    Thread.Sleep(delay);
                    itemsRef.Swap(xs => xs.Reverse().ToArray());
                    latch.Signal();
                })
                {
                    IsBackground = true
                };
                thread.Start();
            }

            latch.Wait();

            CollectionAssert.AreEqual(items, itemsRef.Value);
        }
Ejemplo n.º 6
0
 public void WaitForEventWithTimeout() {
     TestTool.RunTasks(ThreadCount,
                       () => {
                           var countdown = new CountdownLatch(5);
                           bool result = countdown.WaitOne(TimeSpan.FromMilliseconds(5));
                           Assert.IsFalse(result);
                       });
 }
        public void Retry_Queue_Receives_Initial_Failures()
        {
            using (var serviceBusRuntime = Create.MsmqRuntime <IContract>())
            {
                ServiceBusTest tester = new ServiceBusTest(serviceBusRuntime);

                string message            = "Publish this message";
                ContractImplementation ci = new ContractImplementation();
                ci.SetFailCount(1);

                tester.OnlyRetryOnce();
                tester.AddTestListener();

                tester.AddTestSubscription(ci, new PassThroughMessageFilter());

                bool failFirst     = false;
                bool deliverSecond = false;

                tester.StartAndStop(() =>
                {
                    CountdownLatch latch = new CountdownLatch(2 + 1);

                    serviceBusRuntime.MessageDelivered += (o, mdea) =>
                    {
                        int tick; if ((tick = latch.Tick()) == 0)
                        {
                            deliverSecond = true;
                        }
                        Console.WriteLine("Tick deliver " + tick);
                    };
                    serviceBusRuntime.MessageDeliveryFailed += (o, mdfea) =>
                    {
                        int tick; if ((tick = latch.Tick()) == 1)
                        {
                            failFirst = true;
                        }
                        Console.WriteLine("Tick fail " + tick);
                    };

                    serviceBusRuntime.PublishOneWay(new PublishRequest(typeof(IContract), "PublishThis", message));

                    // Wait for delivery
                    latch.Handle.WaitOne(TimeSpan.FromMinutes(1), false); // give it a minute
                });

                Assert.AreEqual(true, failFirst);
                Assert.AreEqual(true, deliverSecond);

                Assert.AreEqual(1, ci.PublishedCount);
                Assert.AreEqual(message, ci.PublishedMessages[0]);


                tester.VerifyQueuesEmpty();
            }
        }
Ejemplo n.º 8
0
        public void Ack()
        {
            simpleClient.ack();

            ackLatch.Wait(2000);
            Assert.IsTrue(ackFlag, "Expected ack flag to be set");

            ackLatch = new CountdownLatch(1);
            simpleClient.ack();
            ackLatch.Wait(2000);
            Assert.IsFalse(ackFlag, "Expected ack flag to be cleared");
        }
 public TestActor(Inbox inbox, CountdownLatch latch)
 {
     _latch = latch;
     inbox.Loop(loop =>
     {
         loop.Receive <TConsumer>(m =>
         {
             _latch.CountDown();
             loop.Continue();
         });
     });
 }
Ejemplo n.º 10
0
 public void Start(String ip, int port, CountdownLatch latch)
 {
     try
     {
         _webapp = WebApp.Start <Startup>(String.Format("http://{0}:{1}", ip, port));
         PacChatServer.GetServer().Logger.Info("Bind success. REST Server is listening on " + ip + ":" + port);
         latch.Signal();
     } catch (Exception e)
     {
         PacChatServer.GetServer().Logger.Error(e);
     }
 }
Ejemplo n.º 11
0
        public void Run()
        {
            Stopwatch timer = Stopwatch.StartNew();

            FiberFactory fiberFactory = () => new ThreadPoolFiber();

            const int channelCount = 10000;
            const int seedCount    = 500;

            var channels = new Channel <string> [channelCount];

            var complete = new Future <int>();

            var latch = new CountdownLatch(channelCount * seedCount, complete.Complete);

            for (int i = 0; i < channelCount; i++)
            {
                int channelNumber = i;
                channels[i] = new ConsumerChannel <string>(fiberFactory(), x =>
                {
                    if (channelNumber < channels.Length - 1)
                    {
                        channels[channelNumber + 1].Send(x);
                    }

                    latch.CountDown();
                });
            }

            for (int i = 0; i < seedCount; i++)
            {
                channels[i].Send("Hi");

                for (int j = 0; j < i; j++)
                {
                    latch.CountDown();
                }
            }

            bool completed = complete.WaitUntilCompleted(24.Seconds());

            timer.Stop();

            if (!completed)
            {
                Console.WriteLine("Process did not complete");
                return;
            }

            Console.WriteLine("Processed {0} messages in with {1} channels in {2}ms", seedCount, channelCount, timer.ElapsedMilliseconds);

            Console.WriteLine("That's {0} messages per second!", ((long)seedCount * channelCount * 1000) / timer.ElapsedMilliseconds);
        }
Ejemplo n.º 12
0
        public void Error()
        {
            // Test synchronous RPC:
            try
            {
                simpleClient.error();
                Assert.Fail("Expected " + typeof(TestError).Name + " to be thrown");
            }
            catch (TestError)
            {
                // Expected
            }
            catch (Exception e)
            {
                Assert.Fail("Unexpected error: " + e);
            }

            // Test asynchronous RPC (future):
            var future = new CallFuture <object>();

            simpleClient.error(future);
            try
            {
                future.WaitForResult(2000);
                Assert.Fail("Expected " + typeof(TestError).Name + " to be thrown");
            }
            catch (TestError)
            {
            }

            Assert.IsNotNull(future.Error);
            Assert.AreEqual(typeof(TestError), future.Error.GetType());
            Assert.IsNull(future.Result);

            // Test asynchronous RPC (callback):
            Exception errorRef = null;
            var       latch    = new CountdownLatch(1);

            simpleClient.error(new CallbackCallFuture <object>(
                                   result => Assert.Fail("Expected " + typeof(TestError).Name),
                                   exception =>
            {
                errorRef = exception;
                latch.Signal();
            }));

            Assert.IsTrue(latch.Wait(2000), "Timed out waiting for error");
            Assert.IsNotNull(errorRef);
            Assert.AreEqual(typeof(TestError), errorRef.GetType());
        }
Ejemplo n.º 13
0
        private void StartNetworkService()
        {
            CountdownLatch latch = new CountdownLatch(1);

            this.Network = new ChatServer(this, protocolProvider, latch);
            _            = this.Network.Bind(new IPEndPoint(ServerSettings.SERVER_HOST, ServerSettings.SERVER_PORT));

            RestAPI = new RestServer();
            RestAPI.Start(ServerSettings.WEBSERVER_HOST, ServerSettings.WEBSERVER_PORT, latch);

            latch.Wait();

            new ConsoleManager();
        }
Ejemplo n.º 14
0
        bool RunTest <T1, T2>(int consumerCount, int messageCount, Future <int> complete, Func <T1> value1Provider,
                              Func <T2> value2Provider, out int totalMessageCount)
        {
            var engine = new DynamicRoutingEngine(new PoolFiber());

            int joinCount = (messageCount / 2) * (messageCount / 2) * consumerCount;

            totalMessageCount = consumerCount * messageCount + joinCount;
            var latch = new CountdownLatch(totalMessageCount, complete.Complete);

            int countA = 0;
            int countB = 0;
            int countC = 0;

            engine.Configure(x =>
            {
                for (int i = 0; i < consumerCount; i++)
                {
                    x.Receive <A>(m =>
                    {
                        Interlocked.Increment(ref countA);
                        latch.CountDown();
                    });
                    x.Receive <B>(m =>
                    {
                        Interlocked.Increment(ref countB);
                        latch.CountDown();
                    });
                }
            });

            //var visualizer = new RoutingEngineTextVisualizer();
            //visualizer.Output = s => Console.WriteLine(s);
            //visualizer.Visit(engine);

            for (int i = 0; i < messageCount; i += 2)
            {
                engine.Send(value1Provider());
                engine.Send(value2Provider());
            }

            bool waitUntilCompleted = complete.WaitUntilCompleted(30.Seconds());

            Console.WriteLine("Consumed A: " + countA);
            Console.WriteLine("Consumed B: " + countB);
            Console.WriteLine("Consumed C: " + countC);


            return(waitUntilCompleted);
        }
Ejemplo n.º 15
0
        public void Run()
        {
            Stopwatch timer = Stopwatch.StartNew();

            FiberFactory fiberFactory = () => new ThreadPoolFiber();

            const int channelCount = 10000;
            const int seedCount = 500;

            var channels = new Channel<string>[channelCount];

            var complete = new Future<int>();

            var latch = new CountdownLatch(channelCount*seedCount, complete.Complete);

            for (int i = 0; i < channelCount; i++)
            {
                int channelNumber = i;
                channels[i] = new ConsumerChannel<string>(fiberFactory(), x =>
                    {
                        if (channelNumber < channels.Length - 1)
                            channels[channelNumber + 1].Send(x);

                        latch.CountDown();
                    });
            }

            for (int i = 0; i < seedCount; i++)
            {
                channels[i].Send("Hi");

                for (int j = 0; j < i; j++)
                    latch.CountDown();
            }

            bool completed = complete.WaitUntilCompleted(24.Seconds());

            timer.Stop();

            if (!completed)
            {
                Console.WriteLine("Process did not complete");
                return;
            }

            Console.WriteLine("Processed {0} messages in with {1} channels in {2}ms", seedCount, channelCount, timer.ElapsedMilliseconds);

            Console.WriteLine("That's {0} messages per second!", ( (long)seedCount * channelCount * 1000) / timer.ElapsedMilliseconds);
        }
Ejemplo n.º 16
0
        //[Test]
        public void PerformanceTest()
        {
            const int  threadCount   = 8;
            const long runTimeMillis = 10 * 1000L;


            long rpcCount = 0;

            int[] runFlag = { 1 };

            var startLatch = new CountdownLatch(threadCount);

            for (int ii = 0; ii < threadCount; ii++)
            {
                new Thread(() =>
                {
                    {
                        try
                        {
                            startLatch.Signal();
                            startLatch.Wait(2000);

                            while (Interlocked.Add(ref runFlag[0], 0) == 1)
                            {
                                Interlocked.Increment(ref rpcCount);
                                Assert.AreEqual("Hello, World!", simpleClient.hello("World!"));
                            }
                        }
                        catch (Exception e)
                        {
                            Console.WriteLine(e);
                        }
                    }
                }).Start();
            }

            startLatch.Wait(2000);
            Thread.Sleep(2000);
            Interlocked.Exchange(ref runFlag[0], 1);

            string results = "Completed " + rpcCount + " RPCs in " + runTimeMillis +
                             "ms => " + ((rpcCount / (double)runTimeMillis) * 1000) + " RPCs/sec, " +
                             (runTimeMillis / (double)rpcCount) + " ms/RPC.";

            Debug.WriteLine(results);
        }
Ejemplo n.º 17
0
        public void Should_work()
        {
            Stopwatch timer = Stopwatch.StartNew();

            FiberFactory fiberFactory = () => new ThreadPoolFiber();

            const int channelCount = 10000;
            const int seedCount    = 500;

            var channels = new Channel <string> [channelCount];

            var completed = new Future <int>();

            var latch = new CountdownLatch(channelCount * seedCount, completed.Complete);

            for (int i = 0; i < channelCount; i++)
            {
                int channelNumber = i;
                channels[i] = new ConsumerChannel <string>(fiberFactory(), x =>
                {
                    if (channelNumber < channels.Length - 1)
                    {
                        channels[channelNumber + 1].Send(x);
                    }

                    latch.CountDown();
                });
            }

            for (int i = 0; i < seedCount; i++)
            {
                channels[i].Send("Hi");

                for (int j = 0; j < i; j++)
                {
                    latch.CountDown();
                }
            }

            completed.WaitUntilCompleted(24.Seconds()).ShouldBeTrue();

            timer.Stop();

            Trace.WriteLine("Elapsed Time: " + timer.ElapsedMilliseconds + "ms");
        }
Ejemplo n.º 18
0
        public void ResetWaitForConsumers() {
            TestTool.RunTasks(ThreadCount,
                              () => {
                                  var countdown = new CountdownLatch(0);
                                  var result = countdown.WaitOne();
                                  Assert.IsTrue(result);

                                  countdown.Reset(5);
                                  result = countdown.WaitOne(TimeSpan.FromMilliseconds(5));
                                  Assert.IsFalse(result);

                                  for(var i = 0; i < 5; i++) {
                                      ThreadPool.QueueUserWorkItem(state => countdown.Set());
                                  }
                                  result = countdown.WaitOne();
                                  Assert.IsTrue(result);
                              });
        }
Ejemplo n.º 19
0
        bool SameMessageTypeTest <TInput, TConsumer>(int messageCount, Future <int> complete, Func <TInput> messageProvider)
        {
            var latch = new CountdownLatch(messageCount, complete.Complete);

            ActorFactory <TestActor <TConsumer> > factory = ActorFactory.Create(inbox => new TestActor <TConsumer>(inbox, latch));
            ActorRef actor = factory.GetActor();

            for (int i = 0; i < messageCount; i++)
            {
                actor.Send(messageProvider());
            }

            bool completed = complete.WaitUntilCompleted(30.Seconds());

            actor.Exit();

            return(completed);
        }
Ejemplo n.º 20
0
 public void ResetWaitForConsumers()
 {
     CountdownLatch countdown = new CountdownLatch(0);
     bool result = countdown.WaitOne();
     Assert.IsTrue(result);
     countdown.Reset(5);
     result = countdown.WaitOne(TimeSpan.FromMilliseconds(5));
     Assert.IsFalse(result);
     for (int i = 0; i < 5; i++)
     {
         ThreadPool.QueueUserWorkItem(delegate
         {
             countdown.Set();
         });
     }
     result = countdown.WaitOne();
     Assert.IsTrue(result);
 }
Ejemplo n.º 21
0
        public void ResetWaitForConsumers()
        {
            CountdownLatch countdown = new CountdownLatch(0);
            bool           result    = countdown.WaitOne();

            Assert.IsTrue(result);
            countdown.Reset(5);
            result = countdown.WaitOne(TimeSpan.FromMilliseconds(5));
            Assert.IsFalse(result);
            for (int i = 0; i < 5; i++)
            {
                ThreadPool.QueueUserWorkItem(delegate
                {
                    countdown.Set();
                });
            }
            result = countdown.WaitOne();
            Assert.IsTrue(result);
        }
        // AVRO-625 [Test]
        // Currently, SocketTransceiver does not permit out-of-order requests on a stateful connection.
        public void Test()
        {
            var waitLatch       = new CountdownLatch(1);
            var simpleResponder = new SimpleResponder(waitLatch);

            server = new SocketServer("localhost", 0, simpleResponder);

            server.Start();

            int port = server.Port;

            transceiver = new SocketTransceiver("localhost", port);
            proxy       = new GenericRequestor(transceiver, SimpleResponder.Protocol);

            // Step 1:
            proxy.GetRemote(); // force handshake

            new Thread(x =>
            {
                // Step 2a:
                waitLatch.Wait();

                var ack = new GenericRecord(SimpleResponder.Protocol.Messages["ack"].Request);
                // Step 2b:
                proxy.Request("ack", ack);
            }).Start();


            /*
             * 3. Execute the Client.hello("wait") RPC, which will block until the
             *    Client.ack() call has completed in the background thread.
             */

            var request = new GenericRecord(SimpleResponder.Protocol.Messages["hello"].Request);

            request.Add("greeting", "wait");

            var response = (string)proxy.Request("hello", request);

            // 4. If control reaches here, both RPCs have executed concurrently
            Assert.AreEqual("wait", response);
        }
Ejemplo n.º 23
0
 public void WaitForEventToRun()
 {
     int count = 5000;
     CountdownLatch countdown = new CountdownLatch(count);
     bool[] done = new bool[count];
     for (int i = 0; i < count; i++)
     {
         int j = i;
         ThreadPool.QueueUserWorkItem(delegate
         {
             done[j] = true;
             countdown.Set();
         });
     }
     bool result = countdown.WaitOne();
     Assert.IsTrue(result);
     for (int i = 0; i < count; i++)
     {
         Assert.IsTrue(done[i], "{0} was not set to true", i);
     }
 }
Ejemplo n.º 24
0
        public void Run(PipelineRunner instance, int iterationCount)
        {
            var complete = new ManualResetEvent(false);

            var latch = new CountdownLatch(10, () => complete.Set());

            for (int i = 0; i < 10; i++)
            {
                ThreadPool.QueueUserWorkItem(x =>
                {
                    for (int j = 0; j < iterationCount / 10; j++)
                    {
                        instance.SendMessage();
                    }

                    latch.CountDown();
                });
            }

            complete.WaitOne(5.Minutes());
        }
Ejemplo n.º 25
0
        public void Should_perform_admirably()
        {
            var random = new Random();

            _count = 50000;

            _updateValues = Enumerable.Range(0, _count)
                            .Select(x => random.Next(1, 1000))
                            .Select(x => x > 960 ? 1000 : x)
                            .Select(x => new UpdateValue(x, random.Next(1, 500000) / 100m))
                            .ToList();

            var input = new ChannelAdapter();

            using (input.Connect(x =>
            {
                x.AddConsumerOf <UpdateValue>()
                .UsingInstance()
                .Of <TestInstance>()
                .DistributedBy(msg => msg.Id)
                .PersistUsingNHibernate()
                .UsingSessionProvider(m => SessionFactory.OpenSession())
                .OnChannel(m => m.UpdateValueChannel)
                .CreateNewInstanceBy(m => new TestInstance(m.Id));
            }))
            {
                var complete = new Future <int>();
                var latch    = new CountdownLatch(_count, complete.Complete);

                _stopwatch = Stopwatch.StartNew();
                UpdateValue.SetReceivedCallback(x => latch.CountDown());

                _updateValues.Each(input.Send);

                complete.WaitUntilCompleted(2.Minutes()).ShouldBeTrue();

                _stopwatch.Stop();
            }
        }
        void waitForDeliveries(int deliveryCount, int failureCount, bool includeFailures, TimeSpan timeout, Action inner)
        {
            using (CountdownLatch latch = new CountdownLatch(deliveryCount))
            {
                using (CountdownLatch failLatch = new CountdownLatch(failureCount))
                {
                    EventHandler <MessageDeliveryEventArgs>       delivered      = (o, mdea) => { Console.WriteLine("s");  latch.Tick(); };
                    EventHandler <MessageDeliveryFailedEventArgs> deliveryFailed = (o, mdfa) => { Console.WriteLine("f"); failLatch.Tick(); };

                    serviceBusRuntime.MessageDelivered += delivered;
                    if (includeFailures)
                    {
                        serviceBusRuntime.MessageDeliveryFailed += deliveryFailed;
                    }

                    try
                    {
                        StartAndStop(() =>
                        {
                            inner();

                            if (!WaitHandle.WaitAll(new WaitHandle[] { latch.Handle, failLatch.Handle }, timeout))
                            {
                                throw new TimeoutException("timeout expired");
                            }
                        });
                    }
                    finally
                    {
                        serviceBusRuntime.MessageDelivered -= delivered;
                        if (includeFailures)
                        {
                            serviceBusRuntime.MessageDeliveryFailed -= deliveryFailed;
                        }
                    }
                }
            }
        }
Ejemplo n.º 27
0
        public void WaitForEventToRun()
        {
            int            count     = 5000;
            CountdownLatch countdown = new CountdownLatch(count);

            bool[] done = new bool[count];
            for (int i = 0; i < count; i++)
            {
                int j = i;
                ThreadPool.QueueUserWorkItem(delegate
                {
                    done[j] = true;
                    countdown.Set();
                });
            }
            bool result = countdown.WaitOne();

            Assert.IsTrue(result);
            for (int i = 0; i < count; i++)
            {
                Assert.IsTrue(done[i], "{0} was not set to true", i);
            }
        }
Ejemplo n.º 28
0
        public void WaintForEventToRun() {
            const int count = 50;

            TestTool.RunTasks(ThreadCount,
                              () => {
                                  var countdown = new CountdownLatch(count);
                                  var done = new bool[count];


                                  for(int i = 0; i < count; i++) {
                                      var j = i;
                                      ThreadPool.QueueUserWorkItem(delegate {
                                                                       done[j] = true;
                                                                       countdown.Set();
                                                                   });
                                  }

                                  bool result = countdown.WaitOne();
                                  Assert.IsTrue(result);

                                  for(var i = 0; i < count; i++)
                                      Assert.IsTrue(done[i], "{0} was not set to true", i);
                              });
        }
 public SimpleResponder(CountdownLatch waitLatch)
     : base(Protocol)
 {
     this.waitLatch = waitLatch;
 }
Ejemplo n.º 30
0
 public void WaitForEventWithTimeout()
 {
     CountdownLatch countdown = new CountdownLatch(5);
     bool result = countdown.WaitOne(TimeSpan.FromMilliseconds(5));
     Assert.IsFalse(result);
 }
Ejemplo n.º 31
0
        public void TaskManagerTest()
        {
            using (var host = new ServiceHost(typeof(MessageQueue)))
            {
                var binding = new NetTcpBinding();
                binding.TransactionFlow = true;
                binding.TransactionProtocol = TransactionProtocol.WSAtomicTransactionOctober2004;
                binding.TransferMode = TransferMode.Streamed;

                host.AddServiceEndpoint(
                    typeof(IMessageQueue),
                    binding,
                    c_queueUrl
                );

                host.Open();

                var cf = new ChannelFactory<IAsyncMessageQueue>(binding, c_queueUrl);

                var queuesrv = cf.CreateChannel();
                string qn = Guid.NewGuid().ToString("N");

                const int mcnt = 3;

                for (int i = 0; i < mcnt; i++)
                {
                    queuesrv.PutMessage(qn, new Message(), TimeSpan.MaxValue);
                }

                var latch = new CountdownLatch(mcnt);

                TaskManager tm = new TaskManager(() => cf.CreateChannel());
                tm.Tasks.Add(
                    new TaskInfo
                    {
                        Queue = qn,
                        Task = new TestTask(() => latch.Signal()),
                        VisibilitySpan = TimeSpan.FromMinutes(1),
                        MaxInstances = mcnt,
                        PollSpan =
                        TimeSpan.FromMilliseconds(500)
                    });

                tm.Start();

                Assert.IsTrue(latch.Wait(6000));
            }
        }
Ejemplo n.º 32
0
 public ChatNetworkServer(PacChatServer server, ProtocolProvider protocolProvider, CountdownLatch latch)
 {
     this.Server           = server;
     this.protocolProvider = protocolProvider;
     this.latch            = latch;
 }
Ejemplo n.º 33
0
 public TypeWaiter(Type type, CountdownLatch countdownLatch)
 {
     _type           = type;
     _countdownLatch = countdownLatch;
 }
Ejemplo n.º 34
0
 public void WaitForConsumersDoesNotWaitIfConsumersAreZero()
 {
     bool result = new CountdownLatch(0).WaitOne();
     Assert.IsTrue(result);
 }
Ejemplo n.º 35
0
        public void Run()
        {
            Stopwatch timer = Stopwatch.StartNew();

            const int actorCount = 20;
            const int pingCount  = 4000;

            var actors = new ActorRef[actorCount + 1];

            var complete = new Future <int>();

            var latch = new CountdownLatch(actorCount * pingCount, complete.Complete);

            for (int i = actorCount; i >= 0; i--)
            {
                actors[i] = AnonymousActor.New(inbox =>
                {
                    var pong = new Pong();

                    var server = actors[(i + 1)];

                    inbox.Loop(loop =>
                    {
                        loop.Receive <Request <Ping> >(request =>
                        {
                            request.Respond(pong);
                            loop.Continue();
                        });
                    });


                    if (i < actorCount)
                    {
                        var ping  = new Ping();
                        int count = 0;

                        Action loop = null;
                        loop        = () =>
                        {
                            server.Request(ping, inbox)
                            .Receive <Response <Pong> >(response =>
                            {
                                latch.CountDown();
                                count++;
                                if (count < pingCount)
                                {
                                    loop();
                                }
                            });
                        };

                        loop();
                    }
                });
            }

            bool completed = complete.WaitUntilCompleted(5.Minutes());

            timer.Stop();

            for (int i = 0; i < actorCount; i++)
            {
                actors[i].Exit();
                actors[i] = null;
            }

            if (!completed)
            {
                Console.WriteLine("Process did not complete");
                return;
            }

            Console.WriteLine("Processed {0} messages in with {1} actors in {2}ms", pingCount, actorCount, timer.ElapsedMilliseconds);

            Console.WriteLine("That's {0} messages per second!", ((long)pingCount * actorCount * 2 * 1000) / timer.ElapsedMilliseconds);
        }
Ejemplo n.º 36
0
        public ChatSocketServer(PacChatServer server, ProtocolProvider protocolProvider, CountdownLatch latch) : base(server, protocolProvider, latch)
        {
            this.bossGroup   = new MultithreadEventLoopGroup(1);
            this.workerGroup = new MultithreadEventLoopGroup();
            this.bootstrap   = new ServerBootstrap();

            this.bootstrap
            .Group(bossGroup, workerGroup)
            //.Option(ChannelOption.SoBacklog, 100)
            //.Handler(new LoggingHandler("SRV-LSTN"))
            .Channel <TcpServerSocketChannel>()
            .ChildOption(ChannelOption.TcpNodelay, true)
            .ChildOption(ChannelOption.SoKeepalive, true);
        }
Ejemplo n.º 37
0
 public ChatServer(PacChatServer server, ProtocolProvider protocolProvider, CountdownLatch latch) : base(server, protocolProvider, latch)
 {
     this.bootstrap.ChildHandler(new ChannelInitializer(this));
 }
Ejemplo n.º 38
0
        public void WaitForConsumersDoesNotWaitIfConsumersAreZero()
        {
            bool result = new CountdownLatch(0).WaitOne();

            Assert.IsTrue(result);
        }
Ejemplo n.º 39
0
 public void reset()
 {
     allMessages = new CountdownLatch(5);
 }
Ejemplo n.º 40
0
        public void Run()
        {
            Stopwatch timer = Stopwatch.StartNew();

            const int channelCount = 10000;
            const int seedCount    = 500;

            var channels    = new UntypedChannel[channelCount];
            var connections = new ChannelConnection[channelCount];

            var complete = new Future <int>();

            var latch = new CountdownLatch(channelCount * seedCount, complete.Complete);

            for (int i = 0; i < channelCount; i++)
            {
                int channelNumber = i;
                channels[i]    = new ChannelAdapter();
                connections[i] = channels[i].Connect(x =>
                {
                    x.AddConsumerOf <AMessage>()
                    .UsingConsumer(message =>
                    {
                        if (channelNumber < channels.Length - 1)
                        {
                            channels[channelNumber + 1].Send(message);
                        }

                        latch.CountDown();
                    });
                });
            }

            var body = new AMessage();

            for (int i = 0; i < seedCount; i++)
            {
                channels[i].Send(body);

                for (int j = 0; j < i; j++)
                {
                    latch.CountDown();
                }
            }

            bool completed = complete.WaitUntilCompleted(2.Minutes());

            timer.Stop();

            connections.Each(x => x.Dispose());


            if (!completed)
            {
                Console.WriteLine("Process did not complete");
                return;
            }

            Console.WriteLine("Processed {0} messages in with {1} channels in {2}ms", seedCount, channelCount,
                              timer.ElapsedMilliseconds);

            Console.WriteLine("That's {0} messages per second!", ((long)seedCount * channelCount * 1000) / timer.ElapsedMilliseconds);
        }
Ejemplo n.º 41
0
        public void Should_perform_admirably()
        {
            var random = new Random();

            _count = 50000;

            _updateValues = Enumerable.Range(0, _count)
                .Select(x => random.Next(1, 1000))
                .Select(x => x > 960 ? 1000 : x)
                .Select(x => new UpdateValue(x, random.Next(1, 500000)/100m))
                .ToList();

            var input = new ChannelAdapter();
            using (input.Connect(x =>
                {
                    x.AddConsumerOf<UpdateValue>()
                        .UsingInstance()
                        .Of<TestInstance>()
                        .DistributedBy(msg => msg.Id)
                        .PersistUsingNHibernate()
                        .UsingSessionProvider(m => SessionFactory.OpenSession())
                        .OnChannel(m => m.UpdateValueChannel)
                        .CreateNewInstanceBy(m => new TestInstance(m.Id));
                }))
            {
                var complete = new Future<int>();
                var latch = new CountdownLatch(_count, complete.Complete);

                _stopwatch = Stopwatch.StartNew();
                UpdateValue.SetReceivedCallback(x => latch.CountDown());

                _updateValues.Each(input.Send);

                complete.WaitUntilCompleted(2.Minutes()).ShouldBeTrue();

                _stopwatch.Stop();
            }
        }