public async Task ProcessServerPackagesSequence()
        {
            var port = this.GetPortNumber(PacketServerPort);

            var serializer = new BinarySerializer(BinarySerializationMethod.UnsafeSerialization);
            var queue      = new WaitableQueue <Packet>();

            using (var packetServer = new PacketServer(IPAddress.Any, port))
            {
                packetServer.OnNewPacketReceived += (sender, value) => queue.Enqueue(value);
                packetServer.Start();

                using (var client = new TcpClient("localhost", port))
                    using (var stream = client.GetStream())
                    {
                        var packetSequence = PacketFixture.GetPacketSequence(PacketSequenceLength);

                        foreach (var packet in packetSequence)
                        {
                            await serializer.Serialize(packet, stream).WithTimeOut(Timeout);
                        }

                        foreach (var packet in packetSequence)
                        {
                            var answer = await queue.Dequeue(Timeout);

                            Assert.AreEqual <PacketEx>(packet, answer);
                        }
                    }
            }
        }
        public async Task ProcessDuplexExchange()
        {
            var port = this.GetPortNumber(PacketServerPort);

            var serializer = new BinarySerializer(BinarySerializationMethod.UnsafeSerialization);
            var queue      = new WaitableQueue <Packet>();

            using (var packetServer = new PacketServer(IPAddress.Any, port))
            {
                packetServer.OnNewPacketReceived += (sender, value) => queue.Enqueue(value);
                packetServer.Start();

                using (var client = new TcpClient("localhost", port))
                    using (var stream = client.GetStream())
                    {
                        var serverSequence = PacketFixture.GetPacketSequence(PacketSequenceLength);
                        var clientSequence = PacketFixture.GetPacketSequence(PacketSequenceLength);

                        foreach (var(serverPacket, clientPacket) in serverSequence.JoinByIndex(clientSequence))
                        {
                            await Task.WhenAll(packetServer.SendPacket(serverPacket),
                                               serializer.Serialize(clientPacket, stream));

                            var results = await Task.WhenAll(queue.Dequeue(Timeout), serializer.Deserialize <Packet>(stream).WithTimeOut(Timeout));

                            Assert.AreEqual <PacketEx>(clientPacket, results[0]);
                            Assert.AreEqual <PacketEx>(serverPacket, results[1]);
                        }
                    }
            }
        }
        public async Task ConcurrentAccess()
        {
            var queue = new WaitableQueue <int>();

            var sequence = new int[128];

            for (var i = 0; i < sequence.Length; ++i)
            {
                sequence[i] = i;
            }

            Parallel.ForEach(sequence, value => queue.Enqueue(value));

            var dequeued = new List <int>();

            try
            {
                while (true)
                {
                    dequeued.Add(await queue.Dequeue(TimeSpan.FromSeconds(1)));
                }
            }
            catch (TimeoutException)
            {
                //ok
            }

            dequeued.Sort();

            Assert.AreEqual(sequence.Length, dequeued.Count);
            Assert.IsTrue(dequeued.SequenceEqual(sequence));
        }
        public async Task OneElementInQueue()
        {
            var queue = new WaitableQueue <int>();

            var testElement = 1;

            queue.Enqueue(testElement);

            var result = await queue.Dequeue();

            Assert.AreEqual(testElement, result);
        }
        public async Task DequeueTimeout()
        {
            var queue = new WaitableQueue <int>();

            try
            {
                await queue.Dequeue(TimeSpan.FromSeconds(1));
            }
            catch (TimeoutException)
            {
                //ok
                return;
            }

            Assert.Fail("Should throw exception");
        }
        public async Task MultipleElementInQueue()
        {
            var queue = new WaitableQueue <int>();

            for (var i = 0; i < 10; ++i)
            {
                queue.Enqueue(i);
            }

            for (var i = 0; i < 10; ++i)
            {
                var result = await queue.Dequeue();

                Assert.AreEqual(i, result);
            }
        }
Esempio n. 7
0
        /// <summary>
        ///   Initializes a new instance of the <see cref = "OnlineNUnitClient" /> class.
        /// </summary>
        public OnlineNUnitClient(ConnectionProtocol connectionProtocol, bool logPhotonClientMessages = false)
        {
            this.Id = Interlocked.Increment(ref curentId);
            this.LogPhotonClientMessages = logPhotonClientMessages;

            this.autoResetEventInit     = new AutoResetEvent(false);
            this.OperationResponseQueue = new WaitableQueue <OperationResponse>();
            this.EventQueue             = new WaitableQueue <EventData>();

            this.Peer = new PhotonPeer(this, connectionProtocol)
            {
                DebugOut = DebugLevel.INFO
            };
            this.Peer.SerializationProtocolType = SerializationProtocol.GpBinaryV18;

            ServicePointManager.ServerCertificateValidationCallback = this.ValidateServerCert;

            this.fiber.Start();
        }
        public async Task ProcessDuplexExchangeConcurrent()
        {
            var port = this.GetPortNumber(PacketServerPort);

            var serializer = new BinarySerializer(BinarySerializationMethod.UnsafeSerialization);
            var queue      = new WaitableQueue <Packet>();

            using (var packetServer = new PacketServer(IPAddress.Any, port))
            {
                packetServer.OnNewPacketReceived += (sender, value) => queue.Enqueue(value);
                packetServer.Start();

                using (var client = new TcpClient("localhost", port))
                    using (var stream = client.GetStream())
                    {
                        var  serverSequence = PacketFixture.GetPacketSequence(PacketSequenceLength);
                        Task serverTask     = null;
                        foreach (var packet in serverSequence)
                        {
                            var task = packetServer.SendPacket(packet);
                            serverTask = serverTask?.ContinueWith(t => task).Unwrap() ?? task;
                        }

                        var clientSequence = PacketFixture.GetPacketSequence(PacketSequenceLength);
                        var clientTask     = Task.CompletedTask;
                        foreach (var packet in clientSequence)
                        {
                            // ReSharper disable once AccessToDisposedClosure
                            clientTask = clientTask.ContinueWith(t => serializer.Serialize(packet, stream)).Unwrap();
                        }

                        await Task.WhenAll(serverTask, clientTask).WithTimeOut(Timeout);

                        foreach (var(serverPacket, clientPacket) in serverSequence.JoinByIndex(clientSequence))
                        {
                            var results = await Task.WhenAll(queue.Dequeue(Timeout), serializer.Deserialize <Packet>(stream).WithTimeOut(Timeout));

                            Assert.AreEqual <PacketEx>(clientPacket, results[0]);
                            Assert.AreEqual <PacketEx>(serverPacket, results[1]);
                        }
                    }
            }
        }
        public async Task CheckConcurrentSequenceOrder()
        {
            var queue = new WaitableQueue <int>();

            var sequence = new int[128];

            for (var i = 0; i < sequence.Length; ++i)
            {
                sequence[i] = i;
            }

            var task = Task.Delay(0);

            for (int i = 0; i < sequence.Length; i++)
            {
                var queueItem = i;
                task = task.ContinueWith(t => queue.Enqueue(queueItem));
            }

            await task;

            var dequeued = new List <int>();

            try
            {
                while (true)
                {
                    dequeued.Add(await queue.Dequeue(TimeSpan.FromSeconds(1)));
                }
            }
            catch (TimeoutException)
            {
                //ok
            }

            Assert.AreEqual(sequence.Length, dequeued.Count);
            Assert.IsTrue(dequeued.SequenceEqual(sequence));
        }
Esempio n. 10
0
        private void StartProcess()
        {
            var startinfo = new System.Diagnostics.ProcessStartInfo();
            var cmd       = this.Description.CommandLine;
            var args      =
                System.Text.RegularExpressions.Regex.Matches(cmd, @"(?:""[^""]+?"")|(?:\S+)")
                .Cast <System.Text.RegularExpressions.Match>()
                .Select(match => match.ToString())
                .ToArray();

            startinfo.WorkingDirectory       = this.Description.BasePath;
            startinfo.UseShellExecute        = false;
            startinfo.FileName               = args.First();
            startinfo.Arguments              = String.Join(" ", args.Skip(1));
            startinfo.CreateNoWindow         = true;
            startinfo.ErrorDialog            = false;
            startinfo.RedirectStandardInput  = true;
            startinfo.RedirectStandardOutput = true;
            startinfo.RedirectStandardError  = true;
            startinfo.StandardOutputEncoding = System.Text.Encoding.ASCII;
            startinfo.StandardErrorEncoding  = System.Text.Encoding.Default;
            processCancellationToken         = new CancellationTokenSource();
            var cancel = processCancellationToken.Token;

            process     = System.Diagnostics.Process.Start(startinfo);
            pipePackets = new WaitableQueue <byte[]>();
            var stdout = process.StandardOutput.BaseStream;
            var stdin  = process.StandardInput.BaseStream;
            var stderr = process.StandardError;

            stdErrorTask = Task.Run(async() => {
                try {
                    Logger logger = new Logger(typeof(CustomFilterContentSink), this.Description.Name);
                    while (!cancel.IsCancellationRequested)
                    {
                        var line = await stderr.ReadLineAsync().ConfigureAwait(false);
                        if (line == null)
                        {
                            break;
                        }
                        if (Description.Logging)
                        {
                            logger.Debug(line);
                        }
                    }
                    stderr.Close();
                }
                catch (System.IO.IOException) {
                }
                catch (ObjectDisposedException) {
                }
            });
            stdOutTask = Task.Run(async() => {
                try {
                    long pos   = 0;
                    var buffer = new byte[1024 * 15];
                    while (!cancel.IsCancellationRequested)
                    {
                        var len = await stdout.ReadAsync(buffer, 0, buffer.Length, cancel).ConfigureAwait(false);
                        System.Console.WriteLine("stdout {0}", len);
                        if (len <= 0)
                        {
                            break;
                        }
                        Sink.OnContent(new Content(lastContent.Stream, lastContent.Timestamp, pos, buffer, 0, len));
                        pos += len;
                    }
                    stdout.Close();
                }
                catch (System.IO.IOException) {
                }
                catch (ObjectDisposedException) {
                }
                finally {
                    System.Console.WriteLine("stdoutclosed");
                }
            });
            writable  = true;
            stdInTask = Task.Run(async() => {
                try {
                    while (!cancel.IsCancellationRequested)
                    {
                        var packet = await pipePackets.DequeueAsync(cancel).ConfigureAwait(false);
                        if (packet != null)
                        {
                            await stdin.WriteAsync(packet, 0, packet.Length, cancel).ConfigureAwait(false);
                            if (pipePackets.IsEmpty)
                            {
                                await stdin.FlushAsync().ConfigureAwait(false);
                            }
                        }
                        else
                        {
                            stdin.Close();
                            break;
                        }
                    }
                }
                catch (System.IO.IOException) {
                }
                catch (ObjectDisposedException) {
                }
                finally {
                    writable = false;
                    System.Console.WriteLine("stdinclosed");
                }
                //TODO:子プロセスが死んだ時に上流か下流かに伝える必要がある
            });
        }