Example #1
17
        private TestKitBase(TestKitAssertions assertions, ActorSystem system, Config config, string actorSystemName, string testActorName)
        {
            if(assertions == null) throw new ArgumentNullException("assertions");
            if(system == null)
            {
                var configWithDefaultFallback = config.SafeWithFallback(_defaultConfig);
                system = ActorSystem.Create(actorSystemName ?? "test", configWithDefaultFallback);
            }

            _assertions = assertions;
            _system = system;
            system.RegisterExtension(new TestKitExtension());
            system.RegisterExtension(new TestKitAssertionsExtension(assertions));
            _testKitSettings = TestKitExtension.For(_system);
            _queue = new BlockingQueue<MessageEnvelope>();
            _log = Logging.GetLogger(system, GetType());
            _eventFilterFactory = new EventFilterFactory(this);
            if (string.IsNullOrEmpty(testActorName))
                testActorName = "testActor" + _testActorId.IncrementAndGet();

            var testActor = CreateTestActor(system, testActorName);
            //Wait for the testactor to start
            AwaitCondition(() =>
            {
                var repRef = testActor as RepointableRef;
                return repRef == null || repRef.IsStarted;
            }, TimeSpan.FromSeconds(5), TimeSpan.FromMilliseconds(10));

            if(!(this is NoImplicitSender))
            {
                InternalCurrentActorCellKeeper.Current = (ActorCell)((ActorRefWithCell)testActor).Underlying;
            }
            _testActor = testActor;

        }
        /// <summary>
        /// Initializes a new instance of the <see cref="ShardedMongoServerProxy"/> class.
        /// </summary>
        /// <param name="server">The server.</param>
        /// <param name="instances">The instances.</param>
        /// <param name="connectionQueue">The state change queue.</param>
        /// <param name="connectionAttempt">The connection attempt.</param>
        /// <remarks>This constructor is used when the instances have already been instructed to connect.</remarks>
        protected MultipleInstanceMongoServerProxy(MongoServer server, IEnumerable<MongoServerInstance> instances, BlockingQueue<MongoServerInstance> connectionQueue, int connectionAttempt)
        {
            _state = MongoServerState.Connecting;
            _server = server;
            _connectedInstances = new ConnectedInstanceCollection();
            _connectionAttempt = connectionAttempt;

            _outstandingInstanceConnections = connectionQueue.Count;
            ThreadPool.QueueUserWorkItem(_ =>
            {
                while (connectionQueue.Count > 0)
                {
                    var instance = connectionQueue.Dequeue();
                    Interlocked.Decrement(ref _outstandingInstanceConnections);
                }
            });

            // It's important to have our own copy of this list because it might get modified during iteration. 
            _instances = instances.ToList();
            foreach (var instance in instances)
            {
                instance.StateChanged += InstanceStateChanged;
                ProcessInstanceStateChange(instance);
            }
        }
Example #3
0
        public void EnqueueBeforeDequeueTest()
        {
            var queue = new BlockingQueue<object>();
            var isEnqueued = new ManualResetEvent(false);
            var isDequeued = new ManualResetEvent(false);

            object value = null;

            ThreadPool.QueueUserWorkItem(_ =>
            {
                queue.Enqueue(new object());
                isEnqueued.Set();
            });
            ThreadPool.QueueUserWorkItem(_ =>
            {
                isEnqueued.WaitOne();
                value = queue.Dequeue();
                isDequeued.Set();
            });

            if (!isDequeued.WaitOne(10))
                Assert.Fail("Dequeue after Enqueue failed: Event hasn't been raised");

            if(value == null)
                Assert.Fail("Dequeue after Enqueue failed: Wrong value returned");
        }
Example #4
0
        public BackendManager(string backendurl, Options options, IBackendWriter statwriter, LocalDatabase database)
        {
            m_options = options;
            m_backendurl = backendurl;
            m_statwriter = statwriter;
            m_taskControl = statwriter as BasicResults;
            m_db = new DatabaseCollector(database, statwriter);

            m_backend = DynamicLoader.BackendLoader.GetBackend(m_backendurl, m_options.RawOptions);
            if (m_backend == null)
                throw new Exception(string.Format("Backend not supported: {0}", m_backendurl));

            if (!m_options.NoEncryption)
            {
                m_encryption = DynamicLoader.EncryptionLoader.GetModule(m_options.EncryptionModule, m_options.Passphrase, m_options.RawOptions);
                if (m_encryption == null)
                    throw new Exception(string.Format("Encryption method not supported: ", m_options.EncryptionModule));
            }

            if (m_taskControl != null)
                m_taskControl.StateChangedEvent += (state) => {
                    if (state == TaskControlState.Abort)
                        m_thread.Abort();
                };
            m_queue = new BlockingQueue<FileEntryItem>(options.SynchronousUpload ? 1 : (options.AsynchronousUploadLimit == 0 ? int.MaxValue : options.AsynchronousUploadLimit));
            m_thread = new System.Threading.Thread(this.ThreadRun);
            m_thread.Name = "Backend Async Worker";
            m_thread.IsBackground = true;
            m_thread.Start();
        }
Example #5
0
 public virtual string BeginGet(string key) {
   BlockingQueue q  = new BlockingQueue();
   this._dht.AsGet(key, q);
   string tk = this.GenToken(key);
   this._bqs.Add(tk, q);
   return tk;
 }
Example #6
0
        public EventQueue(IVsStatusbar statusBar)
        {
            this._statusBar = statusBar;
            _queue = new BlockingQueue<Action>();

            _queueTask = Task.Run(() => ProcessQueue());
        }
        /// <summary>
        /// Creates a new <c>SingleThreadExecutor</c> using a custom thread priority.
        /// </summary>
        /// <param name="priority">
        /// The priority to assign the thread.
        /// </param>
        public SingleThreadExecutor(ThreadPriority priority) {
            _actions = new BlockingQueue<Action>();
            _running = new AtomicBoolean(false);
            _shuttingDown = new AtomicBoolean(false);

            _priority = priority;
        }
Example #8
0
        public BackgroundWorker()
        {
            _queue = new BlockingQueue<Action>();
            _cancellationTokenSource = new CancellationTokenSource();

            Start();
        }
 public StaSynchronizationContext()
     : base()
 {
     mQueue = new BlockingQueue<SendOrPostCallbackItem>();
      mStaThread = new StaThread(mQueue);
      mStaThread.Start();
 }
Example #10
0
        private TestKitBase(TestKitAssertions assertions, ActorSystem system, Config config, string actorSystemName = null)
        {
            if(assertions == null) throw new ArgumentNullException("assertions");
            if(system == null)
            {
                var configWithDefaultFallback = config.SafeWithFallback(_defaultConfig);
                system = ActorSystem.Create(actorSystemName ?? "test", configWithDefaultFallback);
            }

            _assertions = assertions;
            _system = system;
            system.RegisterExtension(new TestKitExtension());
            system.RegisterExtension(new TestKitAssertionsExtension(assertions));
            _testKitSettings = TestKitExtension.For(_system);
            _queue = new BlockingQueue<MessageEnvelope>();
            _log = Logging.GetLogger(system, GetType());


            var testActor = CreateTestActor(system, "testActor" + _testActorId.IncrementAndGet());
            _testActor = testActor;
            //Wait for the testactor to start
            AwaitCondition(() =>
            {
                var repRef = _testActor as RepointableRef;
                return repRef == null || repRef.IsStarted;
            }, TimeSpan.FromSeconds(1), TimeSpan.FromMilliseconds(10));
        }
        public LocalAssetServer()
        {
            bool yapfile;
            this._assetRequests = new BlockingQueue<ARequest>();
            yapfile = System.IO.File.Exists("assets.yap");

            OpenSim.Framework.Console.MainConsole.Instance.WriteLine("Local Asset Server class created");
            try
            {
                db = Db4oFactory.OpenFile("assets.yap");
                OpenSim.Framework.Console.MainConsole.Instance.WriteLine("Db4 Asset database  creation");
            }
            catch (Exception e)
            {
                db.Close();
                OpenSim.Framework.Console.MainConsole.Instance.WriteLine("Db4 Asset server :Constructor - Exception occured");
                OpenSim.Framework.Console.MainConsole.Instance.WriteLine(e.ToString());
            }
            if (!yapfile)
            {
                this.SetUpAssetDatabase();
            }
            this._localAssetServerThread = new Thread(new ThreadStart(RunRequests));
            this._localAssetServerThread.IsBackground = true;
            this._localAssetServerThread.Start();
        }
Example #12
0
 public EventQueueServer(HttpListener server)
 {
     this.server = server;
     eventQueue = new BlockingQueue<EventQueueEvent>();
     running = true;
     currentID = 1;
 }
Example #13
0
        public JabberNetwork(SocialUser user, byte[] certData, 
      BlockingQueue queue, string jabber_port)
        {
            _local_user = user;
              _queue = queue;
              _friends = new Dictionary<string, List<string>>();
              _online = false;
              _auth_pending = false;
              _pres_sent = false;
              _jclient = new JabberClient();

              _jclient.Port = Int32.Parse(jabber_port);
              _jclient.AutoReconnect = 30F;
              _jclient.AutoStartTLS = true;
              _jclient.KeepAlive = 30F;
              _jclient.AutoPresence = false;
              _jclient.AutoRoster = false;
              _jclient.LocalCertificate = null;
              _jclient.Resource = SVPNRESOURCE +
            _local_user.Fingerprint.Substring(0, 10);

              _jclient.OnError += HandleOnError;
              _jclient.OnAuthError += HandleOnAuthError;

            #if SVPN_NUNIT
              _jclient.OnReadText += HandleOnReadText;
              _jclient.OnWriteText += HandleOnWriteText;
            #endif
              _jclient.OnAuthenticate += HandleOnAuthenticate;
              _jclient.OnPresence += HandleOnPresence;
              _jclient.OnIQ += HandleOnIQ;
              _jclient.OnInvalidCertificate += HandleInvalidCert;
        }
Example #14
0
 public void Many_consumers_with_timeouts()
 {
     BlockingQueue<string> q = new BlockingQueue<string>();
     Thread c1 = new Thread(MultiConsumer);
     Thread c2 = new Thread(MultiConsumer);
     Thread c3 = new Thread(MultiConsumer);
     c1.IsBackground = true;
     c2.IsBackground = true;
     c3.IsBackground = true;
     Tuplet<BlockingQueue<string>, string, TimeSpan, ManualResetEvent> v1
         = new Tuplet<BlockingQueue<string>, string, TimeSpan, ManualResetEvent>(q, "x", TimeSpan.FromSeconds(1), new ManualResetEvent(false));
     c1.Start(v1);
     Tuplet<BlockingQueue<string>, string, TimeSpan, ManualResetEvent> v2
         = new Tuplet<BlockingQueue<string>, string, TimeSpan, ManualResetEvent>(q, "x", TimeSpan.FromSeconds(1), new ManualResetEvent(false));
     c2.Start(v2);
     Tuplet<BlockingQueue<string>, string, TimeSpan, ManualResetEvent> v3
         = new Tuplet<BlockingQueue<string>, string, TimeSpan, ManualResetEvent>(q, "x", TimeSpan.FromSeconds(1), new ManualResetEvent(false));
     c3.Start(v3);
     q.Enqueue("foo");
     Assert.IsTrue(v1.Item4.WaitOne(2000, false), "thread 1 did not finish");
     Assert.IsTrue(v2.Item4.WaitOne(2000, false), "thread 2 did not finish");
     Assert.IsTrue(v3.Item4.WaitOne(2000, false), "thread 3 did not finish");
     bool gotValue = false;
     foreach(Tuplet<BlockingQueue<string>, string, TimeSpan, ManualResetEvent> v in new Tuplet<BlockingQueue<string>, string, TimeSpan, ManualResetEvent>[] { v1, v2, v3 }) {
         if(v.Item2 == "foo") {
             gotValue = true;
             Assert.Less(v.Item3.TotalSeconds, 1);
         } else {
             Assert.IsNull(v.Item2);
             Assert.GreaterOrEqual(v.Item3.TotalSeconds, 0.95);
         }
     }
     Assert.IsTrue(gotValue);
 }
Example #15
0
 static Receiver()
 {
     if (rcvBlockingQ == null)
         rcvBlockingQ = new BlockingQueue<SvcMsg>();
     if (rcvBlockingQServer == null)
         rcvBlockingQServer = new BlockingQueue<SvcMsg>();
 }
Example #16
0
        public void TestBlockingQueueStress()
        {
            var queue = new BlockingQueue<int>(1);

            var rnd = new ThreadLocal<Random>(() => new Random());
            var generatedTotal = 0;
            var consummedTotal = 0;

            var producers = TestMonitorSimple.RunSimultanously(5, () =>
            {
                for (var i = 0; i < 1e6; i++)
                {
                    var value = rnd.Value.Next(100);
                    Interlocked.Add(ref generatedTotal, value);
                    queue.AddIfNotCompleted(value);
                }
            }, false);

            var consumers = TestMonitorSimple.RunSimultanously(5, () =>
            {
                foreach (var value in queue.GetConsumingEnumerable())
                {
                    Interlocked.Add(ref consummedTotal, value);
                }
            }, false);

            producers.ForEach(t => t.Join());
            queue.CompleteAdding();

            consumers.ForEach(t => t.Join());

            Assert.IsTrue(consummedTotal == generatedTotal);
        }
Example #17
0
        public MessageController(AWatcherService Watcher, IDBController Controller)
        {
            this.queue = new BlockingQueue<ParsedMessage>();
            this.watcher = Watcher;
            this.controller = Controller;

            this.watcher.RecievedMessage += Watcher_RecievedMessage;
        }
Example #18
0
 public SpotifyPool(int size)
 {
     this.connectionList = new List<ISpotify>();
     this.connectionQueue = new BlockingQueue<ISpotify>(size);
     this.poolSize = size;
     this.userName = null;
     this.password = null;
 }
Example #19
0
        /// <summary>
        ///   Initializes a new instance of the <see cref = "TestClient" /> class.
        /// </summary>
        /// <param name = "useTcp">
        ///   The use Tcp.
        /// </param>
        public TestClient(bool useTcp)
        {
            this.autoResetEventInit = new AutoResetEvent(false);
            this.operationResponseQueue = new BlockingQueue<OperationResponse>(1000, 1000);
            this.eventQueue = new BlockingQueue<EventData>(1000, 1000);

            this.PhotonClient = new LitePeer(this, useTcp) { DebugOut = DebugLevel.INFO };
            this.fiber.Start();
        }
 public StaSynchronizationContext()
     : base()
 {
     mQueue = new BlockingQueue<SendOrPostCallbackItem>();
     mStaThread = new StaThread(mQueue, this);
     mStaThread.Start();
     oldSync = SynchronizationContext.Current;
     SynchronizationContext.SetSynchronizationContext(this);
 }
Example #21
0
 public ThreadedMockSender(ISender ReturnPath, object State,
     IDataHandler Receiver, int RemoveNPTypes, double drop_rate) :
   base(ReturnPath, State, Receiver, RemoveNPTypes, drop_rate)
 {
   _queue = new BlockingQueue();
   Thread runner = new Thread(ThreadRun);
   runner.IsBackground = true;
   runner.Start();
 }
Example #22
0
        public Writer(IConnection connection, Stream stream, BlockingQueue<Notification> queue, Archive archive)
        {
            this.connection = connection;
            this.stream = stream;
            this.queue = queue;
            this.archive = archive;

            thread = new Thread(new ThreadStart(Run));
            thread.Start();
        }
Example #23
0
        public void CreateAndUseBlockingQueue()
        {
            BlockingQueue<int> queue = new BlockingQueue<int>(1);

            Thread thread = new Thread(new ThreadStart(delegate() { queue.Enqueue(1); }));
            thread.Start();

            int element = queue.Dequeue();
            Assert.AreEqual(1, element);
        }
Example #24
0
        public ConnectionIoActor(IWorkScheduler worker, IBufferAllocator bufferAllocator)
        {
            _sendQueue = new BlockingQueue<IOState>();
            _receiveQueue = new BlockingQueue<IOState>();

            _bufferAllocator = bufferAllocator;
            _worker = worker;
            _worker.QueueForever(SendEnqueued, 1.Milliseconds());
            _worker.QueueForever(ReceiveEnqueued, 1.Milliseconds());
        }
 public EndpointSession(DefaultEndpointClient client)
 {
     this.client = client;
     this.flushing = new ThreadSafe.Boolean(false);
     this.closed = new ThreadSafe.Boolean(false);
     this.flushingOp = new ThreadSafe.AtomicReference<WriteOp>(null);
     this.sessionFuture = new ThreadSafe.AtomicReference<IConnectFuture>(null);
     this.opQueue = new BlockingQueue<WriteOp>(client.Config.EndpointSessionSendBufferSize);
     
 }
    public CommService()
    {
      // Only one service, the first, should create the queue

      if(BlockingQ == null)
        BlockingQ = new BlockingQueue<Message>();

      SetWindowPos(GetConsoleWindow(), (IntPtr)0, 100, 100, 400, 600, 0);
      //Console.Title = "CommService";
    }
Example #27
0
    public DualButtonInput(IPConnection ipcon, BlockingQueue<char> keyQueue)
    {
        this.keyQueue = keyQueue;

        byte buttonL;
        byte buttonR;

        if (Config.UID_DUAL_BUTTON_BRICKLET[0] == null)
        {
            System.Console.WriteLine("Not Configured: Dual Button 1");
        }
        else
        {
            dualButton1 = new BrickletDualButton(Config.UID_DUAL_BUTTON_BRICKLET[0], ipcon);

            try
            {
                dualButton1.GetButtonState(out buttonL, out buttonR);
                System.Console.WriteLine("Found: Dual Button 1 ({0})",
                                         Config.UID_DUAL_BUTTON_BRICKLET[0]);
            }
            catch (TinkerforgeException)
            {
                System.Console.WriteLine("Not Found: Dual Button 1 ({0})",
                                         Config.UID_DUAL_BUTTON_BRICKLET[0]);
            }

            dualButton1.StateChanged += StateChanged1CB;
        }

        if (Config.UID_DUAL_BUTTON_BRICKLET[1] == null)
        {
            System.Console.WriteLine("Not Configured: Dual Button 2");
        }
        else
        {
            dualButton2 = new BrickletDualButton(Config.UID_DUAL_BUTTON_BRICKLET[1], ipcon);

            try
            {
                dualButton2.GetButtonState(out buttonL, out buttonR);
                System.Console.WriteLine("Found: Dual Button 2 ({0})",
                                         Config.UID_DUAL_BUTTON_BRICKLET[0]);
            }
            catch (TinkerforgeException)
            {
                System.Console.WriteLine("Not Found: Dual Button 2 ({0})",
                                         Config.UID_DUAL_BUTTON_BRICKLET[0]);
            }

            dualButton2.StateChanged += StateChanged2CB;
        }

        pressTimer = new Timer(delegate(object state) { PressTick(); }, null, 100, 100);
    }
Example #28
0
 public void Dequeue_times_out_as_specified()
 {
     BlockingQueue<string> q = new BlockingQueue<string>();
     DateTime start = GlobalClock.UtcNow;
     string x;
     Assert.IsFalse(q.TryDequeue(TimeSpan.FromSeconds(1), out x));
     Assert.IsNull(x);
     TimeSpan elapsed = GlobalClock.UtcNow.Subtract(start);
     Assert.GreaterOrEqual(elapsed.TotalSeconds, 0.95);
     Assert.LessOrEqual(elapsed.TotalSeconds, 1.1d);
 }
Example #29
0
 public void Dequeue_on_closed_queue_throws()
 {
     BlockingQueue<string> q = new BlockingQueue<string>();
     q.Enqueue("foo");
     Assert.IsFalse(q.IsClosed);
     q.Close();
     Assert.IsTrue(q.IsClosed);
     string x = q.Dequeue();
     Assert.AreEqual("foo", x);
     x = q.Dequeue();
 }
Example #30
0
        /// <summary>
        ///   Initializes a new instance of the <see cref = "TestClient" /> class.
        /// </summary>
        /// <param name = "useTcp">
        ///   The use Tcp.
        /// </param>
        public TestClient(bool useTcp)
        {
            ConnectionProtocol protocol = useTcp ? ConnectionProtocol.Tcp : ConnectionProtocol.Udp;

            this.autoResetEventInit = new AutoResetEvent(false);
            this.operationResponseQueue = new BlockingQueue<OperationResponse>(1000, 1000);
            this.eventQueue = new BlockingQueue<EventData>(1000, 1000);

            this.PhotonClient = new PhotonPeer(this, protocol) { DebugOut = DebugLevel.INFO };
            this.fiber.Start();
        }
Example #31
0
 public Taker(TestFairCallQueue _enclosing, BlockingQueue <Schedulable> aCq, int maxCalls
              , string tag, CountDownLatch latch)
 {
     this._enclosing = _enclosing;
     // if >= 0 means we will only take the matching tag, and put back
     // anything else
     // total calls taken, accurate if we aren't interrupted
     // the last thing we took
     // maximum calls to take
     this.maxCalls = maxCalls;
     this.cq       = aCq;
     this.tag      = tag;
     this.uip      = new UserIdentityProvider();
     this.latch    = latch;
 }
Example #32
0
 public HikePubSub()
 {
     listeners = new Dictionary <string, List <Listener> >();
     mQueue    = new BlockingQueue(100);
     try
     {
         mThread      = new Thread(new ThreadStart(startPubSub));
         mThread.Name = "PUBSUB THREAD";
         mThread.Start();
     }
     catch (ThreadStartException e)
     {
         // do something here
     }
 }
Example #33
0
        public TrafficHandler(ITrafficHandler eventHandler)
        {
            this.eventHandler = eventHandler;
            reliableMonitor   = new ReliableMonitor(this);

            packetReceivedCallbacks = new Dictionary <Packet.Reliability, Action <Packet> >();
            packetReceivedCallbacks[Packet.Reliability.None]       = packet => { };
            packetReceivedCallbacks[Packet.Reliability.Ack]        = OnAckReceived;
            packetReceivedCallbacks[Packet.Reliability.Reliable]   = OnReliableReceived;
            packetReceivedCallbacks[Packet.Reliability.Unreliable] = OnUnreliableReceived;

            latestReceived = new BoundedList <Packet>(1024 * 8);

            pendingOut = new BlockingQueue <Packet>();
        }
Example #34
0
        public void Remove_First_Items()
        {
            var queue = new BlockingQueue <string>();

            queue.Enqueue("a");
            queue.Enqueue("b");
            queue.Enqueue("c");

            Assert.AreEqual("a", queue.RemoveFirst());
            Assert.AreEqual("b", queue.RemoveFirst());

            Assert.AreEqual(1, queue.Count);

            Assert.AreEqual("c", queue.Dequeue());
        }
        public void BlockingQueue_TryPeek_Collection_Size_is_not_Changed_When_Item_Peeked_from_Collection()
        {
            //Arrange
            var blockingQueue = new BlockingQueue <int>();

            blockingQueue.Enqueue(42);
            var startCount = blockingQueue.Count;

            //Act
            blockingQueue.TryPeek(out int item);

            //Assert
            Assert.AreEqual(1, startCount);
            Assert.AreEqual(1, blockingQueue.Count);
        }
Example #36
0
        //----< subscribe to new message events >------------------------

        public Client1()
        {
            InitializeComponent();
            block = new byte[BlockSize];
            Title = "CLIENT1 VISUAL";
            Console.WriteLine("\n Console of client titled: {0}", Title);

            rcvThread = new Thread(new ThreadStart(this.ThreadProc));
            rcvThread.IsBackground = true;
            rcvThread.Start();

            OnNewMessage           += new NewMessage(OnNewMessageHandler);
            ConnectButton.IsEnabled = true;    //set to false- can't connect.
            SendButton.IsEnabled    = false;
            //DELETE THIS TEXT TO USE GUI ----------------------------------------------------------------------------
            string remoteAddress = RemoteAddressTextBox.Text;
            string remotePort    = RemotePortTextBox.Text;
            string endPoint      = Comm <Client1> .makeEndPoint(remoteAddress, remotePort, "IClient1");

            comm.rcvr.CreateRecvChannel(endPoint);
            SendButton.IsEnabled = true;
            channel = comm.sndr.CreateSendChannel("http://*****:*****@"..\..\..\Client\ToSend\");

            string localPort = LocalPortTextBox.Text;
            string endpoint  = "http://*****:*****@"..\..\..\Xmlfilesc1");
                String postString         = bq.deQ();
                listBox1.Items.Insert(0, postString);             //CLIENT 1 DEFINING MESSAGE BODY HERE
                Message postMessage = makeMessage("KUNAL PALIWAL", "http://localhost:4000/IClient", endpoint);
                postMessage.body = postString;
                postMessage.from = Comm <Client1> .makeEndPoint(RemoteAddressTextBox.Text, RemotePortTextBox.Text, "IClient1");

                postMessage.time = DateTime.Now;
                postMessage.type = "TEST REQUEST 1";
                comm.sndr.PostMessage(postMessage);
            }
            catch (Exception ex)
            {
                Window temp = new Window();
                temp.Content = ex.Message;
                temp.Height  = 100;
                temp.Width   = 500;
            }
        }
Example #37
0
        public void BlockingQueue_TwoPublishersTwoReaders()
        {
            // arrange
            var dequeuedValues = new ConcurrentDictionary <int, bool>(); // Used to check  blocking queue
            var queue          = new BlockingQueue <int>();

            // act
            Parallel.Invoke(
                () => Publish(queue, 0, 100_000),
                () => Publish(queue, 100_000, 200_000),
                () => Consume(queue, 100_000, dequeuedValues),
                () => Consume(queue, 100_000, dequeuedValues));

            // assert
            Assert.Equal(200_000, dequeuedValues.Count);
        }
Example #38
0
        public void TestSimpleEnqueueDequeue()
        {
            BlockingQueue <int> col = new BlockingQueue <int>();

            for (int i = 0; i < 100; i++)
            {
                Assert.AreEqual(i, col.Count);
                col.Add(i);
            }

            for (int i = 0; i < 100; i++)
            {
                Assert.AreEqual(100 - i, col.Count);
                Assert.AreEqual(i, col.Take());
            }
        }
Example #39
0
    // Use this for initialization
    void Start()
    {
        handle        = new GNS3Handle("192.168.56.1", 3080);
        projectHandle = handle.ProjectHandle("abc46e15-c32a-45ae-9e86-e896ea0afac2");
        StartCoroutine(handle.CheckHealth(
                           () => Debug.Log("Connection is good"),
                           () => Debug.Log("Connection is bad")
                           ));
        StartCoroutine(projectHandle.CheckHealth(
                           () => Debug.Log("Project connection is good"),
                           () => Debug.Log("Project connection is bad")
                           ));

        reader = new BlockingQueue <string>();
        writer = new BlockingQueue <string>();
    }
Example #40
0
        public void XMLRquestHandling(BlockingQueue <string> b)
        {
            XmlTest x = new XmlTest();
            Creator c = new Creator();


            for (int i = 0; i < b.size(); i++)
            {
                Console.Write("\n------------Dequeueing Test Requests---------------\n");
                string      TestRequest = b.deQ();
                List <Test> testList_   = x.parse(TestRequest);
                c.AppDomainCreator(testList_);
                List <TestResults> results = c.getResults();
                resultsBlockingQueue.enQ(results);
            }
        }
Example #41
0
        public Listener(IPEndPoint Endpoint, IList <Client> ClientListType)
        {
            // Create a new TCP/IP socket
            Inner = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            Inner.Bind(Endpoint); // Bind to the local endpoint
            Inner.Listen(50);     // Start listening with a backlog of 50 connections

            Clients  = new List <Client>();
            Messages = new BlockingQueue <ClientMessagePair>();

            ClientConnect         = delegate { };
            ClientDisconnect      = delegate { };
            ClientMessageReceived = delegate { };

            Run = false;
        }
Example #42
0
        public void ShouldBlock_WhenPopFromEmptyQueue()
        {
            // arrange
            var  queue = new BlockingQueue <int>();
            Task pop;
            Task timeout;

            // act
            var actual = Task.WhenAny(
                pop     = Task.Run(() => queue.Pop()),
                timeout = Task.Delay(TimeSpan.FromSeconds(1))).GetAwaiter().GetResult();

            // assert
            Assert.NotSame(pop, actual);
            Assert.Same(timeout, actual);
        }
Example #43
0
 public ConsumerThread(string name, Func <Job, Result> action, BlockingQueue <Job> queue = null) : base(name)
 {
     _action   = action;
     _profile  = SingletonManager.Get <DurationHelp>().GetCustomProfileInfo(name);
     _profile2 = SingletonManager.Get <DurationHelp>().GetCustomProfileInfo(name + "_all");
     _logger   =
         new LoggerAdapter(Name);
     if (queue == null)
     {
         _queue = new BlockingQueue <Job>(32);
     }
     else
     {
         _queue = queue;
     }
 }
        /// <summary>
        /// The BaseDataLayer constructor.
        /// </summary>
        /// <param name="cuda">Specifies the CudaDnn connection to Cuda.</param>
        /// <param name="log">Specifies the Log for output.</param>
        /// <param name="p">Specifies the LayerParameter</param>
        /// <param name="db">Specifies the external database to use.</param>
        /// <param name="evtCancel">Specifies the CancelEvent used to cancel any pre-fetching operations.</param>
        public BasePrefetchingDataLayer(CudaDnn <T> cuda, Log log, LayerParameter p, IXImageDatabase db, CancelEvent evtCancel)
            : base(cuda, log, p, db)
        {
            m_evtCancel              = evtCancel;
            m_rgPrefetch             = new Batch <T> [p.data_param.prefetch];
            m_rgPrefetchFree         = new BlockingQueue <Batch <T> >(m_evtCancel);
            m_rgPrefetchFull         = new BlockingQueue <Batch <T> >(m_evtCancel);
            m_internalThread         = new InternalThread <T>();
            m_internalThread.DoWork += new EventHandler <ActionStateArgs <T> >(m_internalThread_DoWork);

            for (int i = 0; i < m_rgPrefetch.Length; i++)
            {
                m_rgPrefetch[i] = new Batch <T>(cuda, log);
                m_rgPrefetchFree.Push(m_rgPrefetch[i]);
            }
        }
        public void BlockingQueue_Represent_a_Queue()
        {
            //Arrange
            var blockingQueue = new BlockingQueue <int>();

            int[] array = new[] { 0, 1, 2, 3, 4, 6, 7, 8, 9 };

            //Act
            foreach (var n in array)
            {
                blockingQueue.Enqueue(n);
            }

            //Assert
            Assert.IsTrue(blockingQueue.SequenceEqual(array));
        }
Example #46
0
        //Test stub for logger class
        static void Main(String args)
        {
            Logger log = new Logger();
            Dictionary <String, String> example = new Dictionary <String, String>();
            String xmlPath = @"..\..\..\..\Xmlfiles";

            Console.WriteLine("\n Accepting XML Files from path :{0}", xmlPath);
            DirectoryInfo          directoryInfo    = new DirectoryInfo(xmlPath);
            BlockingQueue <string> testRequestQueue = new BlockingQueue <string>();

            if (Directory.Exists(xmlPath))
            {
                string[] fileEntries = Directory.GetFiles(xmlPath);
                Console.WriteLine("\n Accepting Test Requests from Path: {0}  \n", xmlPath);
                foreach (string filename in fileEntries)
                {
                    Console.WriteLine("{0}", Path.GetFileName(filename));
                    testRequestQueue.enQ(File.ReadAllText(filename));
                }
                Console.WriteLine("\n Enqueueing all Test Requests");
                Console.WriteLine("\n Size of Blockingqueue: {0}", testRequestQueue.size());
            }
            else
            {
                Console.WriteLine("No XML was found at the path specified: {0} \n", xmlPath);
            }

            int count = testRequestQueue.size();

            while (count != 0)
            {
                Xmltest     xt   = new Xmltest();
                List <Test> test = xt.parse((String)testRequestQueue.deQ());

                foreach (Test t in test)
                {
                    log.DisplayLog(example, t, "PASS");
                }

                foreach (String l in example.Values)
                {
                    Console.WriteLine("\n {0}", l);
                }
                count--;
            }
            //log.getSavedLogs(0);
        }
Example #47
0
        public void AddTakeMultithreadTest()
        {
            const int ItemsCount = 10000;

            using (var queue = new BlockingQueue <int>())
                using (var barrier = new Barrier(2))
                {
                    ConcurrentBag <int> bag = new ConcurrentBag <int>();

                    var task1 = Task.Run(() =>
                    {
                        barrier.SignalAndWait();
                        Parallel.For(0, ItemsCount, val =>
                        {
                            queue.Add(val);
                            Thread.SpinWait(val % 100);
                        });
                    });

                    var task2 = Task.Run(() =>
                    {
                        barrier.SignalAndWait();
                        Parallel.For(0, 10000, val =>
                        {
                            int res = 0;
                            if (!queue.TryTake(out res, 10000))
                            {
                                Assert.Fail("Value was expected in MemoryQueue");
                            }
                            bag.Add(res);
                            Thread.SpinWait((val + 37) % 100);
                        });
                    });

                    Task.WaitAll(task1, task2);

                    Assert.AreEqual(0, queue.Count);
                    Assert.AreEqual(ItemsCount, bag.Count);

                    var array = bag.ToArray();
                    Array.Sort(array);
                    for (int i = 0; i < array.Length; i++)
                    {
                        Assert.AreEqual(i, array[i], "i != array[i]");
                    }
                }
        }
Example #48
0
        private TestKitBase(ITestKitAssertions assertions, ActorSystem system, Config config, string actorSystemName, string testActorName)
        {
            if (assertions == null)
            {
                throw new ArgumentNullException("assertions");
            }
            if (system == null)
            {
                var configWithDefaultFallback = config.SafeWithFallback(_defaultConfig);
                system = ActorSystem.Create(actorSystemName ?? "test", configWithDefaultFallback);
            }

            _assertions = assertions;
            _system     = system;
            system.RegisterExtension(new TestKitExtension());
            system.RegisterExtension(new TestKitAssertionsExtension(assertions));
            _testKitSettings    = TestKitExtension.For(_system);
            _queue              = new BlockingQueue <MessageEnvelope>();
            _log                = Logging.GetLogger(system, GetType());
            _eventFilterFactory = new EventFilterFactory(this);

            //register the CallingThreadDispatcherConfigurator
            _system.Dispatchers.RegisterConfigurator(CallingThreadDispatcher.Id,
                                                     new CallingThreadDispatcherConfigurator(_system.Settings.Config, _system.Dispatchers.Prerequisites));

            if (string.IsNullOrEmpty(testActorName))
            {
                testActorName = "testActor" + _testActorId.IncrementAndGet();
            }

            var testActor = CreateTestActor(system, testActorName);

            //Wait for the testactor to start
            AwaitCondition(() =>
            {
                var repRef = testActor as IRepointableRef;
                return(repRef == null || repRef.IsStarted);
            }, TimeSpan.FromSeconds(5), TimeSpan.FromMilliseconds(10));

            if (!(this is INoImplicitSender))
            {
                InternalCurrentActorCellKeeper.Current = (ActorCell)((ActorRefWithCell)testActor).Underlying;
            }
            SynchronizationContext.SetSynchronizationContext(
                new ActorCellKeepingSynchronizationContext(InternalCurrentActorCellKeeper.Current));
            _testActor = testActor;
        }
        public void ShouldEnqueAndDequeTheSameMessage()
        {
            BlockingQueue <ThreadMessage> x = new BlockingQueue <ThreadMessage>();
            // ReSharper disable once UseObjectOrCollectionInitializer
            ThreadMessage msg1 = new ThreadMessage(1);

            msg1.Add("Test1", "Some String Value");
            msg1.Add("TEST2", 1);
            msg1.Add("Test3", true);
            x.Enqueue(msg1);
            ThreadMessage msg2 = x.Dequeue();

            Assert.AreEqual(msg1.Cmd, msg2.Cmd);
            Assert.AreEqual(msg1.GetString("Test1"), msg2.GetString("Test1"));
            Assert.AreEqual(msg1.GetInt("Test2"), msg2.GetInt("TEST2"));
            Assert.AreEqual(msg1.GetBool("Test3"), msg2.GetBool("Test3"));
        }
Example #50
0
        /// <summary>
        /// Returns the first non-empty queue with equal or lesser priority
        /// than <i>startIdx</i>.
        /// </summary>
        /// <remarks>
        /// Returns the first non-empty queue with equal or lesser priority
        /// than <i>startIdx</i>. Wraps around, searching a maximum of N
        /// queues, where N is this.queues.size().
        /// </remarks>
        /// <param name="startIdx">the queue number to start searching at</param>
        /// <returns>
        /// the first non-empty queue with less priority, or null if
        /// everything was empty
        /// </returns>
        private BlockingQueue <E> GetFirstNonEmptyQueue(int startIdx)
        {
            int numQueues = this.queues.Count;

            for (int i = 0; i < numQueues; i++)
            {
                int idx = (i + startIdx) % numQueues;
                // offset and wrap around
                BlockingQueue <E> queue = this.queues[idx];
                if (queue.Count != 0)
                {
                    return(queue);
                }
            }
            // All queues were empty
            return(null);
        }
Example #51
0
        public void RethrowException_On_Dispose_By_Default()
        {
            BlockingQueue <string>      work       = new BlockingQueue <string>();
            WorkItemDispatcher <string> dispatcher = new WorkItemDispatcher <string>(
                5, // work in 5 threads
                (data) =>
            {
                throw new Exception(ExceptionMessage);
            },
                work
                );

            work.Enqueue("some work");
            work.ReleaseWaiters();

            Assert.Throws <AggregateException>(() => dispatcher.Dispose());
        }
Example #52
0
        public ZyreEndpoint(string name, Action <string> logger = null) : base(name, Guid.Empty, logger)
        {
#if NET35
            AsyncIO.ForceDotNet.Force();
#endif
            NetMQ.NetMQConfig.Linger = System.TimeSpan.FromSeconds(0);

            _remoteEndpoints = new Dictionary <Guid, RemoteEndpoint>();

            _poller = new NetMQPoller();
            //StartZyre();

            _readyGraphUpdates   = new List <GraphUpdate>();
            _waitingGraphUpdates = new BlockingQueue <GraphUpdate>();
            _updateThread        = new Thread(RunUpdateLoop);
            _updateThread.Start();
        }
        public void BlockingQueue_TryDequeue_is_Cancelled_by_CancellationToken()
        {
            //Arrange
            var blockingQueue           = new BlockingQueue <int>();
            var cancellationTokenSource = new CancellationTokenSource();

            Task.Factory.StartNew(() =>
            {
                Thread.Sleep(500);
                cancellationTokenSource.Cancel();
            });

            //Act
            blockingQueue.TryDequeue(out int item, 5000, cancellationTokenSource.Token);

            //Assert is handled by the ExpectedException
        }
Example #54
0
        static void Main(string[] args)
        {
            BlockingQueue <int> blockingQueue = new BlockingQueue <int>();

            Task.Factory.StartNew(() =>
            {
                Thread.Sleep(1000);
                blockingQueue.Enqueue(42);
            });

            if (blockingQueue.TryDequeue(out int item, 3000))
            {
                Console.WriteLine(item);
            }

            Console.ReadLine();
        }
        public virtual void TestBlocking()
        {
            IQueue4 queue = new BlockingQueue();

            string[] data = new string[] { "a", "b", "c", "d" };
            queue.Add(data[0]);
            Assert.AreSame(data[0], queue.Next());
            BlockingQueueTestCase.NotifyThread notifyThread = new BlockingQueueTestCase.NotifyThread
                                                                  (queue, data[1]);
            notifyThread.Start();
            long start = Runtime.CurrentTimeMillis();

            Assert.AreSame(data[1], queue.Next());
            long end = Runtime.CurrentTimeMillis();

            Assert.IsGreater(500, end - start);
        }
Example #56
0
        public void Simulatanous_Queueing_Enqueuing_Must_Not_Skip_Elements()
        {
            BlockingQueue <string> q = new BlockingQueue <string>();

            int    dequeueCount = 0;
            int    exitCount    = 0;
            Action dequeuer     = () =>
            {
                while (true)
                {
                    string item = q.Dequeue();

                    if (item == null)
                    {
                        // last element reached
                        Interlocked.Increment(ref exitCount);
                        break;
                    }

                    Interlocked.Increment(ref dequeueCount);
                }
            };

            const int Threads = 10;

            for (int i = 0; i < Threads; i++)
            {
                dequeuer.BeginInvoke(null, null);
            }

            // wait until some threads are up and running
            Thread.Sleep(300);

            for (int i = 0; i < QueueItems; i++)
            {
                q.Enqueue(i.ToString());
            }

            q.ReleaseWaiters();
            q.WaitUntilEmpty();
            Thread.Sleep(30);
            Assert.AreEqual(QueueItems, dequeueCount, "Number of Enqueue and Deque calls must be the same");
            Thread.Sleep(200);
            Assert.AreEqual(Threads, exitCount, "All Threads should have exited by now");
        }
Example #57
0
        public void AddTakeSequentialTest()
        {
            const int ItemsCount = 10000;

            using (var queue = new BlockingQueue <int>())
                using (var barrier = new Barrier(2))
                {
                    List <int> bag = new List <int>();

                    var task1 = Task.Run(() =>
                    {
                        barrier.SignalAndWait();
                        for (int val = 0; val < ItemsCount; val++)
                        {
                            queue.Add(val);
                            Thread.SpinWait(val % 100);
                        }
                    });

                    var task2 = Task.Run(() =>
                    {
                        barrier.SignalAndWait();
                        for (int val = 0; val < ItemsCount; val++)
                        {
                            int res = 0;
                            if (!queue.TryTake(out res, 10000))
                            {
                                Assert.Fail("Value was expected in MemoryQueue");
                            }
                            bag.Add(res);
                            Thread.SpinWait((val + 37) % 100);
                        }
                    });

                    Task.WaitAll(task1, task2);

                    Assert.AreEqual(0, queue.Count);
                    Assert.AreEqual(ItemsCount, bag.Count);

                    for (int i = 0; i < bag.Count; i++)
                    {
                        Assert.AreEqual(i, bag[i], "i != bag[i]");
                    }
                }
        }
Example #58
0
        public void ExecuteGetTreatmentWithDependencyMatcherImpressionOnChild()
        {
            //Arrange
            var queue            = new BlockingQueue <KeyImpression>(10);
            var impressionsCache = new InMemoryImpressionsCache(queue);
            var client           = new JSONFileClient(@"Resources\splits_staging_6.json", "", null, null, new SelfUpdatingTreatmentLog(null, 1000, impressionsCache));

            //Act
            var result = client.GetTreatment("test", "test_dependency_segment", null);

            //Assert
            Assert.IsNotNull(result);
            Assert.AreEqual("V1", result);
            var item = queue.Dequeue();

            Assert.AreEqual(item.feature, "test_dependency_segment");
            Assert.IsNull(queue.Dequeue());
        }
        /** @copydoc BaseDataLayer::dispose */
        protected override void dispose()
        {
            m_internalThread.StopInternalThread();

            if (m_rgPrefetchFull != null)
            {
                m_rgPrefetchFull.Dispose();
                m_rgPrefetchFull = null;
            }

            if (m_rgPrefetchFree != null)
            {
                m_rgPrefetchFree.Dispose();
                m_rgPrefetchFree = null;
            }

            base.dispose();
        }
Example #60
0
        public void CreateAndUseBlockingQueueTenTimes()
        {
            BlockingQueue <int> queue = new BlockingQueue <int>(5);

            Thread thread = new Thread(new ThreadStart(delegate() { for (int k = 1; k <= 10; k++)
                                                                    {
                                                                        queue.Enqueue(k);
                                                                    }
                                                       }));

            thread.Start();

            for (int j = 1; j <= 10; j++)
            {
                int element = queue.Dequeue();
                Assert.AreEqual(element, j);
            }
        }