Esempio n. 1
0
        public async Task <R> ExecuteAsync <R>(Query <M, R> query)
        {
            var response = new WriteOnceBlock <object>(r => r);

            _executionPipeline.Post(new QueryRequest(query, response));
            return((R)await response.ReceiveAsync());
        }
        public void BasicUsageTest()
        {
            bool act1 = false, act2 = false;
            var  evt = new CountdownEvent(2);

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

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

            Assert.IsTrue(block.Post(42));
            Assert.IsFalse(block.Post(43));

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

            Assert.IsTrue(act1);
            Assert.IsTrue(act2);
        }
Esempio n. 3
0
        public async Task <R> ExecuteAsync <R>(Command <M, R> command)
        {
            var response = new WriteOnceBlock <object>(r => r);

            _journaler.Post(new CommandRequest(command, response));
            return((R)await response.ReceiveAsync());
        }
Esempio n. 4
0
        public Task ExecuteAsync(Command <M> command)
        {
            var response = new WriteOnceBlock <object>(b => b);

            _journaler.Post(new CommandRequest(command, response));
            return(response.ReceiveAsync());
        }
        public void CloningTest()
        {
            object act1 = null, act2 = null;
            var    evt = new CountdownEvent(2);

            object source  = new object();
            var    block   = new WriteOnceBlock <object> (o => new object());
            var    action1 = new ActionBlock <object> (i =>
            {
                act1 = i;
                evt.Signal();
            });
            var action2 = new ActionBlock <object> (i =>
            {
                act2 = i;
                evt.Signal();
            });

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

            Assert.IsTrue(block.Post(source));

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

            Assert.IsNotNull(act1);
            Assert.IsNotNull(act2);

            Assert.IsFalse(source.Equals(act1));
            Assert.IsFalse(source.Equals(act2));
            Assert.IsFalse(act2.Equals(act1));
        }
Esempio n. 6
0
        public void TestCanceledLinking()
        {
            bool passed = true;

            var cts = new CancellationTokenSource();

            cts.Cancel();
            var options = new DataflowBlockOptions {
                CancellationToken = cts.Token
            };
            var writeOnce = new WriteOnceBlock <int>(x => x, options);
            var target    = new ActionBlock <int>(x => { });

            try
            {
                writeOnce.LinkTo(target);
                Console.WriteLine("Completed without exception - Passed");
            }
            catch (Exception)
            {
                passed = false;
                Console.WriteLine("Completed without exception - FAILED");
            }

            Assert.True(passed, "Test failed.");
        }
Esempio n. 7
0
 public Question(string preamble, string query, IEnumerable<string> answers)
 {
     Preamble = preamble;
     Answers = answers;
     Query = query;
     answerBlock = null;
 }
Esempio n. 8
0
        public void TestWriteOnceBlockConstructor()
        {
            try
            {
                // without option
                var block = new WriteOnceBlock <int>(i => i);
                block = new WriteOnceBlock <int>(null);
                // There is no property to verify. If construction itself fails, there will be an exception.

                //with not cancelled token and default scheduler
                block = new WriteOnceBlock <int>(i => i, new DataflowBlockOptions {
                    MaxMessagesPerTask = 1
                });
                block = new WriteOnceBlock <int>(null, new DataflowBlockOptions {
                    MaxMessagesPerTask = 1
                });
                // There is no property to verify. If construction itself fails, there will be an exception.

                //with a cancelled token and default scheduler
                var token = new CancellationToken(true);
                block = new WriteOnceBlock <int>(i => i, new DataflowBlockOptions {
                    MaxMessagesPerTask = 1, CancellationToken = token
                });
                block = new WriteOnceBlock <int>(null, new DataflowBlockOptions {
                    MaxMessagesPerTask = 1, CancellationToken = token
                });
                // There is no property to verify. If construction itself fails, there will be an exception.
            }
            catch (Exception ex)
            {
                Assert.True(false, "Test failed with exception: " + ex.Message);
            }
        }
Esempio n. 9
0
        // This demonstrates the behavior of the WriteOnceBlock as it's easy to observe.
        //
        // Preface: I hate the name of this block. It's misleading. This should have been
        // called CloneBlock or CacheBlock. WriteOnceBlock sounds like you use the block once
        // and it then self-destructs.

        // How it works is simple, it will accept one published message and reject all other messages
        // coming to it. It will then take the first message and clone it and send it on every request
        // downstream.
        private static async Task WriteBlockBehaviorDemoAsync()
        {
            Console.WriteLine("WriteOneBlockDemo has started!");
            var block = new WriteOnceBlock <string>(input => input); // needs a clone function

            for (int i = 0; i < 5; i++)
            {
                if (block.Post(ProduceTimeData()))
                {
                    Console.WriteLine($"Message {i} was accepted");
                }
                else
                {
                    Console.WriteLine($"Message {i} was rejected");
                }
            }

            // Notice the count is much higher than input count and that I am not
            // waiting on it to signal no more data is coming, as it always has data.
            for (int i = 0; i < 15; i++)
            {
                var output = await block.ReceiveAsync().ConfigureAwait(false);

                Console.WriteLine($"ReceivedMessage {i}: {output}");
            }

            block.Complete();
            await block.Completion.ConfigureAwait(false);

            Console.WriteLine("Finished!");
            Console.ReadKey();
        }
Esempio n. 10
0
        static void Main(string[] args)
        {
            var writeOnceBlock = new WriteOnceBlock <int>(a => a);
            var actionBlock    = new ActionBlock <int>(a => Console.WriteLine($"ActionBlock received {a}"));

            writeOnceBlock.LinkTo(actionBlock);

            for (int i = 0; i < 5; i++)
            {
                if (writeOnceBlock.Post(i))
                {
                    Console.WriteLine($"Accepted {i}");
                }
                else
                {
                    Console.WriteLine($"Rejected {i}");
                }
            }

            for (int i = 0; i < 10; i++) // Receive more than Post
            {
                if (writeOnceBlock.TryReceive(out int result))
                {
                    Console.WriteLine($"Received {result}");
                }
                else
                {
                    Console.WriteLine($"Warning {result}");
                }
            }

            Console.WriteLine("Finished!");
            Console.ReadKey();
        }
        public async Task WriteOnceWithAction()
        {
            var block = new WriteOnceBlock <int>(a => a);
            var print = new ActionBlock <int>(a => Console.WriteLine($"Message: {a}"));

            block.LinkTo(print);

            for (int i = 0; i < 10; i++)
            {
                if (block.Post(i))
                {
                    Console.WriteLine($"Acceped {i}");
                }
                else
                {
                    Console.WriteLine($"Rejected {i}");
                }
            }

            block.Complete();
            await block.Completion;

            print.Complete();
            await print.Completion;

            Console.WriteLine("Done!");
        }
        public void SimpleWriteOnce()
        {
            var block = new WriteOnceBlock <int>(a => a);

            for (int i = 0; i < 10; i++)
            {
                if (block.Post(i))
                {
                    Console.WriteLine($"Acceped {i}");
                }
                else
                {
                    Console.WriteLine($"Rejected {i}");
                }
            }

            for (int i = 0; i < 15; i++)
            {
                if (block.TryReceive(out var val))
                {
                    Console.WriteLine($"Received {val}");
                }
                else
                {
                    Console.WriteLine($"No more messages!");
                }
            }

            Console.WriteLine("Done!");
        }
Esempio n. 13
0
        static void Main(string[] args)
        {
            var buffer = new BufferBlock <int>();

            buffer.Post(1);
            buffer.Post(2);
            buffer.Post(3);

            Console.WriteLine("buffer: " + buffer.Receive());
            Console.WriteLine("buffer: " + buffer.Receive());
            Console.WriteLine("buffer: " + buffer.Receive());

            var broadcast = new BroadcastBlock <int>(i => i);

            broadcast.Post(1);

            Console.WriteLine("broadcast: " + broadcast.Receive());
            Console.WriteLine("broadcast: " + broadcast.Receive());
            Console.WriteLine("broadcast: " + broadcast.Receive());


            var writeOnce = new WriteOnceBlock <int>(i => i);

            writeOnce.Post(1);
            writeOnce.Post(2);
            writeOnce.Post(3);

            Console.WriteLine("write-once: " + writeOnce.Receive());
        }
Esempio n. 14
0
        private void LastMessageDublicate_ThrowTimeout()
        {
            var        nmsProtocol = _stack.GetCodec <NmsCodec>().Protocol;
            var        options     = new NibusOptions();
            NmsMessage lastMessage;

            nmsProtocol.IncomingMessages.TryReceive(null, out lastMessage);
            var query = new NmsRead(Destanation, 2);

            nmsProtocol.OutgoingMessages.Post(query);
            var        wob = new WriteOnceBlock <NmsMessage>(m => m);
            NmsMessage response, response2;

            using (nmsProtocol.IncomingMessages.LinkTo(
                       wob, m => !ReferenceEquals(m, lastMessage) && m.IsResponse && m.ServiceType == query.ServiceType && m.Id == query.Id))
            {
                response = wob.Receive(options.Timeout);
            }
            nmsProtocol.IncomingMessages.TryReceive(null, out lastMessage);
            Assert.That(lastMessage, Is.EqualTo(response));
            var wob2 = new WriteOnceBlock <NmsMessage>(m => m);

            using (nmsProtocol.IncomingMessages.LinkTo(
                       wob2, m => !ReferenceEquals(m, lastMessage) && m.IsResponse && m.ServiceType == query.ServiceType && m.Id == query.Id))
            {
                response2 = wob2.Receive(options.Timeout);
            }
        }
        public void DontOfferTwiceTest()
        {
            var scheduler = new TestScheduler();
            var block     = new WriteOnceBlock <int> (null,
                                                      new DataflowBlockOptions {
                TaskScheduler = scheduler
            });
            var target =
                new TestTargetBlock <int> {
                Postpone = true
            };

            block.LinkTo(target);

            Assert.IsFalse(target.HasPostponed);

            Assert.IsTrue(block.Post(1));

            scheduler.ExecuteAll();

            Assert.IsTrue(target.HasPostponed);

            target.Postpone = false;

            int value;

            Assert.IsTrue(target.RetryPostponed(out value));
            Assert.AreEqual(1, value);

            block.LinkTo(new BufferBlock <int> ());

            scheduler.ExecuteAll();

            Assert.AreEqual(default(int), target.DirectlyAccepted);
        }
        public IEnumerable <string> WriteOnceBlockUsage(int numberOfIteration, int minValue)
        {
            Console.WriteLine($"Inside {nameof(TplDataflow2BufferingBlocksController)} - {nameof(WriteOnceBlockUsage)}");

            var strings = new BlockingCollection <string>();

            // Create the members of the pipeline.
            var WriteOnceBlockGivenInputToASubscriber = new WriteOnceBlock <string>(null);
            var actionBlockSubscriber = new ActionBlock <string>(stringInput =>
                                                                 Functions.AddInputIntoTheGivenList(strings, stringInput, "Subscriber")
                                                                 );

            // Connect the dataflow blocks to form a pipeline.
            WriteOnceBlockGivenInputToASubscriber.LinkTo(actionBlockSubscriber, DataflowOptions.LinkOptions);

            // Start WriteOnceBlockUsage pipeline with the input values.
            for (var i = minValue; i <= minValue + numberOfIteration; i++)
            {
                WriteOnceBlockGivenInputToASubscriber.Post($"Value = {i}");
            }

            // Mark the head of the pipeline as complete.
            WriteOnceBlockGivenInputToASubscriber.Complete();

            // Wait for the last block in the pipeline to process all messages.
            actionBlockSubscriber.Completion.Wait();

            return(strings);
        }
        public void WriteOnceBehaviorTest()
        {
            bool act1 = false, act2 = false;
            var  evt = new CountdownEvent(2);

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

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

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

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

            Assert.IsTrue(act1);
            Assert.IsTrue(act2);

            Assert.IsFalse(broadcast.Post(24));
            Thread.Sleep(300);

            Assert.IsTrue(act1);
            Assert.IsTrue(act2);
        }
Esempio n. 18
0
        public void AsyncReceiveTestCanceled()
        {
            var src = new CancellationTokenSource();

            var block = new WriteOnceBlock <int> (null);
            var task  = block.ReceiveAsync(src.Token);

            Task.Factory.StartNew(() => { Thread.Sleep(800); block.Post(42); });
            Thread.Sleep(50);
            src.Cancel();

            AggregateException ex = null;

            try {
                task.Wait();
            } catch (AggregateException e) {
                ex = e;
            }

            Assert.IsNotNull(ex);
            Assert.IsNotNull(ex.InnerException);
            Assert.IsInstanceOfType(typeof(OperationCanceledException), ex.InnerException);
            Assert.IsTrue(task.IsCompleted);
            Assert.AreEqual(TaskStatus.Canceled, task.Status);
        }
Esempio n. 19
0
        private static WriteOnceBlock <int> ConstructWriteOnce()
        {
            var block = new WriteOnceBlock <int>(i => i);

            block.Post(0);
            return(block);
        }
Esempio n. 20
0
        public async Task DiscoverAllAsync()
        {
            if (IsDiscovering) // only called from the Mainthread -> not racy
            {
                return;
            }

            IsDiscovering            = true;
            m_bRemoteMinVersionError = false;
            m_bLocalMinVersionError  = false;

            m_wbFirstResult = new WriteOnceBlock <DiscoveredServerInfo>((x) => { return(x); }); // no cloning needed
            BinaryWriter reqPacket = DiscoveryPacket_Request.WritePacket();
            List <DiscoveredServerInfo> liResults = new List <DiscoveredServerInfo>();

            await Task.WhenAll(DiscoverAllIPv4Async(reqPacket, liResults)
                               , DiscoverAllIPv6Async(reqPacket, liResults));

            Log.d(TAG, "Done waiting, got " + liResults.Count + " valid replies");
            if (liResults.Count > 0)
            {
                m_wbFirstResult.Post(liResults[0]); // In case we didn't post any first result because the defaultserver wasn't found
            }
            // Remove Servers which were found on an earlier run but not anymore
            for (int i = FoundServer.Count - 1; i >= 0; i--)
            {
                if (!liResults.Contains(FoundServer[i]))
                {
                    FoundServer.RemoveAt(i);
                }
            }

            IsDiscovering = false;
            DisoveryFinished.Invoke(this, new DiscoveryFinishedEventArgs(m_bRemoteMinVersionError, m_bLocalMinVersionError));
        }
Esempio n. 21
0
        public async Task TestWriteOnce()
        {
            var bb = new WriteOnceBlock <int>(null);

            bb.LinkTo(new ActionBlock <int>(i =>
            {
                Thread.Sleep(1000);
                Console.WriteLine("Receiver1:" + i);
            }, new ExecutionDataflowBlockOptions()
            {
                BoundedCapacity = 1
            }));

            bb.LinkTo(new ActionBlock <int>(i =>
            {
                Thread.Sleep(1000);
                Console.WriteLine("Receiver2:" + i);
            }));

            Assert.IsTrue(bb.Post(1));

            Assert.IsFalse(bb.Post(2));
            Assert.IsFalse(await bb.SendAsync(3));
            Assert.IsFalse(bb.Post(4));
            Assert.IsFalse(await bb.SendAsync(5));
        }
Esempio n. 22
0
		public void BasicUsageTest ()
		{
			bool act1 = false, act2 = false;
			var evt = new CountdownEvent (2);

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

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

			Assert.IsTrue (block.Post (42));
			Assert.IsFalse (block.Post (43));

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

			Assert.IsTrue (act1);
			Assert.IsTrue (act2);
		}
        public void TestWriteOnceBlockConstructor()
        {
            try
            {
                // without option
                var block = new WriteOnceBlock<int>(i => i);
                block = new WriteOnceBlock<int>(null);
                // There is no property to verify. If construction itself fails, there will be an exception.

                //with not cancelled token and default scheduler
                block = new WriteOnceBlock<int>(i => i, new DataflowBlockOptions { MaxMessagesPerTask = 1 });
                block = new WriteOnceBlock<int>(null, new DataflowBlockOptions { MaxMessagesPerTask = 1 });
                // There is no property to verify. If construction itself fails, there will be an exception.

                //with a cancelled token and default scheduler
                var token = new CancellationToken(true);
                block = new WriteOnceBlock<int>(i => i, new DataflowBlockOptions { MaxMessagesPerTask = 1, CancellationToken = token });
                block = new WriteOnceBlock<int>(null, new DataflowBlockOptions { MaxMessagesPerTask = 1, CancellationToken = token });
                // There is no property to verify. If construction itself fails, there will be an exception.
            }
            catch (Exception ex)
            {
                Assert.True(false, "Test failed with exception: " + ex.Message);
            }
        }
        public async Task TestConsumeToAccept()
        {
            var wob = new WriteOnceBlock <int>(i => i * 2);

            wob.Post(1);
            await wob.Completion;

            var b2 = new BatchedJoinBlock <int, int>(1);

            wob.LinkTo(b2.Target2, new DataflowLinkOptions {
                PropagateCompletion = true
            });
            Tuple <IList <int>, IList <int> > item2 = await b2.ReceiveAsync();

            Assert.Equal(expected: 0, actual: item2.Item1.Count);
            Assert.Equal(expected: 1, actual: item2.Item2.Count);
            b2.Target1.Complete();

            var b3 = new BatchedJoinBlock <int, int, int>(1);

            wob.LinkTo(b3.Target3, new DataflowLinkOptions {
                PropagateCompletion = true
            });
            Tuple <IList <int>, IList <int>, IList <int> > item3 = await b3.ReceiveAsync();

            Assert.Equal(expected: 0, actual: item3.Item1.Count);
            Assert.Equal(expected: 0, actual: item3.Item2.Count);
            Assert.Equal(expected: 1, actual: item3.Item3.Count);
            b3.Target1.Complete();
            b3.Target2.Complete();

            await Task.WhenAll(b2.Completion, b3.Completion);
        }
Esempio n. 25
0
        public async Task TestCancellationBeforeAndAfterCtor()
        {
            foreach (bool before in DataflowTestHelpers.BooleanValues)
            {
                var cts = new CancellationTokenSource();
                if (before)
                {
                    cts.Cancel();
                }
                var wob = new WriteOnceBlock <int>(null, new DataflowBlockOptions {
                    CancellationToken = cts.Token
                });
                if (!before)
                {
                    cts.Cancel();
                }

                int         ignoredValue;
                IList <int> ignoredValues;

                Assert.NotNull(wob.LinkTo(DataflowBlock.NullTarget <int>()));
                Assert.False(wob.Post(42));
                Task <bool> sendTask = wob.SendAsync(43);
                Assert.True(sendTask.IsCompleted);
                Assert.False(sendTask.Result);
                Assert.False(wob.TryReceive(out ignoredValue));
                Assert.False(((IReceivableSourceBlock <int>)wob).TryReceiveAll(out ignoredValues));
                Assert.NotNull(wob.Completion);

                await Assert.ThrowsAnyAsync <OperationCanceledException>(() => wob.Completion);
            }
        }
Esempio n. 26
0
 public async Task<string> AskAsync(Question question)
 {
     var b = new WriteOnceBlock<string>(s => s);
     question.answerBlock = b;
     // TODO: handle if buffer refuses message? If task.Result is false
     var task = await buf.SendAsync(question);
     return await b.ReceiveAsync();
 }
Esempio n. 27
0
 internal InletCollection(Node node)
 {
     _node = node;
     _cts  = new CancellationTokenSource();
     _buf  = new WriteOnceBlock <bool>(null, new DataflowBlockOptions
     {
         CancellationToken = _cts.Token
     });
 }
 private static WriteOnceBlock<int> ConstructWriteOnceNewWithNMessages(int messagesCount)
 {
     var block = new WriteOnceBlock<int>(i => i);
     for (int i = 0; i < messagesCount; i++)
     {
         block.Post(i);
     }
     return block;
 }
Esempio n. 29
0
        public void Run()
        {
            // Example 1:
            // ____________________________________________
            // Create a WriteOnceBlock<string> object.
            var writeOnceBlock = new WriteOnceBlock <string>(null);

            // Post several messages to the block in parallel. The first
            // message to be received is written to the block.
            // Subsequent messages are discarded.
            Parallel.Invoke(
                () => writeOnceBlock.Post("Message 1"),
                () => writeOnceBlock.Post("Message 2"),
                () => writeOnceBlock.Post("Message 3"));

            // Receive the message from the block.
            Console.WriteLine(writeOnceBlock.Receive());

            /* Sample output:
             * Message 2
             */

            // Example 2
            // ________________________________________________
            // Create a shared CancellationTokenSource object to enable the
            // TrySolution method to be cancelled.
            var cts = new CancellationTokenSource();

            // Create three TransformBlock<int, int> objects.
            // Each TransformBlock<int, int> object calls the TrySolution method.
            Func <int, int> action       = n => TrySolution(n, cts.Token);
            var             trySolution1 = new TransformBlock <int, int>(action);
            var             trySolution2 = new TransformBlock <int, int>(action);
            var             trySolution3 = new TransformBlock <int, int>(action);

            // Post data to each TransformBlock<int, int> object.
            trySolution1.Post(11);
            trySolution2.Post(21);
            trySolution3.Post(31);

            // Call the ReceiveFromAny<T> method to receive the result from the
            // first TransformBlock<int, int> object to finish.
            int result = ReceiveFromAny(trySolution1, trySolution2, trySolution3);

            // Cancel all calls to TrySolution that are still active.
            cts.Cancel();

            // Print the result to the console.
            Console.WriteLine("The solution is {0}.", result);

            cts.Dispose();

            /* Sample output:
             * The solution is 53.
             */
        }
Esempio n. 30
0
        private static WriteOnceBlock <int> ConstructWriteOnceNewWithNMessages(int messagesCount)
        {
            var block = new WriteOnceBlock <int>(i => i);

            for (int i = 0; i < messagesCount; i++)
            {
                block.Post(i);
            }
            return(block);
        }
Esempio n. 31
0
        public async Task TestReserveReleaseConsume()
        {
            var wb = new WriteOnceBlock <int>(i => i * 2);

            wb.Post(1);
            await DataflowTestHelpers.TestReserveAndRelease(wb, reservationIsTargetSpecific : false);

            wb = new WriteOnceBlock <int>(i => i * 2);
            wb.Post(2);
            await DataflowTestHelpers.TestReserveAndConsume(wb, reservationIsTargetSpecific : false);
        }
Esempio n. 32
0
        /// <summary>
        /// Отправляет NMS-сообщение <paramref name="query"/> и ожидает ответа.
        /// Асинхронная операция.
        /// </summary>
        /// <typeparam name="TMessage">Тип сообщения, потомок NmsMessage.</typeparam>
        /// <param name="query">Сообщение-запрос.</param>
        /// <param name="options">Параметры асинхронной операции.</param>
        /// <returns>
        ///  <see cref="Task{TResult}"/> асинхронная операция - ответное сообщение.
        /// </returns>
        /// <exception cref="AggregateException">Призошла ошибка в асинхронном коде. См. <see cref="Exception.InnerException"/></exception>
        /// <exception cref="TimeoutException">Ошибка по таймауту.</exception>
        /// <exception cref="TaskCanceledException">Операция прервана пользователем.</exception>
        /// <exception cref="NibusResponseException">Ошибка NiBUS.</exception>
        public async Task <TMessage> WaitForNmsResponseAsync <TMessage>(TMessage query, NibusOptions options = null)
            where TMessage : NmsMessage
        {
            //Contract.Requires(!IsDisposed);
            //Contract.Requires(
            //    query.Datagram.Destanation.Type == AddressType.Hardware
            //    || query.Datagram.Destanation.Type == AddressType.Net);

            options = GetDefaultOrClone(options);

            // Последнее сообщение в BroadcastBlock всегда остается! Незабываем его фильтровать.
            NmsMessage lastMessage;

            IncomingMessages.TryReceive(null, out lastMessage);

            var wob = new WriteOnceBlock <NmsMessage>(m => m);

            using (IncomingMessages.LinkTo(
                       wob,
                       m => !ReferenceEquals(lastMessage, m) && m.IsResponse && m.ServiceType == query.ServiceType &&
                       (query.Id == 0 || m.Id == query.Id) && (query.Datagram.Destanation == Address.Empty || m.Datagram.Source == query.Datagram.Destanation)))
            {
                for (var i = 0; i < options.Attempts; i++)
                {
                    await OutgoingMessages.SendAsync(query);

                    try
                    {
                        var response =
                            (TMessage)await wob.ReceiveAsync(options.Timeout, options.Token).ConfigureAwait(false);

                        if (response.ErrorCode != 0)
                        {
                            throw new NibusResponseException(response.ErrorCode);
                        }

                        return(response);
                    }
                    catch (TimeoutException)
                    {
                        Logger.Debug("Timeout {0}", i + 1);
                        if (i < options.Attempts - 1)
                        {
                            continue;
                        }
                        throw;
                    }
                }
            }

            // Эта точка недостижима при attempts > 0!
            throw new InvalidOperationException();
        }
Esempio n. 33
0
 public async Task TestPost()
 {
     foreach (int boundedCapacity in new[] { DataflowBlockOptions.Unbounded, 1, 2 })
     {
         var wob = new WriteOnceBlock <int>(i => i, new DataflowBlockOptions {
             BoundedCapacity = boundedCapacity
         });                                                                                                        // options shouldn't affect anything
         Assert.True(wob.Post(1));
         Assert.False(wob.Post(2));
         await wob.Completion;
     }
 }
Esempio n. 34
0
        public ISourceDataflowBuilder <TOutput> WriteOnce(Func <TOutput, TOutput> cloningFunction, DataflowWriteOnceOptions writeOnceOptions)
        {
            if (cloningFunction == null)
            {
                throw new ArgumentNullException("cloningFunction");
            }

            var writeOnceBlock = new WriteOnceBlock <TOutput>(cloningFunction, writeOnceOptions.WriteOnceBlockOptions);

            LinkHelper.Link(_finalSourceBlock, writeOnceBlock, writeOnceOptions.LinkOptions);
            return(new SourceDataflowBuilder <TOutput>(_originalSourceBlock, _finalSourceBlock, writeOnceBlock, _propagateCompletion));
        }
Esempio n. 35
0
        public async Task TestFaultyTarget()
        {
            var wob = new WriteOnceBlock <int>(null);

            wob.LinkTo(new DelegatePropagator <int, int> {
                OfferMessageDelegate = delegate {
                    throw new FormatException();
                }
            });
            wob.Post(42);
            await Assert.ThrowsAsync <FormatException>(() => wob.Completion);
        }
Esempio n. 36
0
		public void LinkAfterPostTest ()
		{
			bool act = false;
			var evt = new ManualResetEventSlim ();

			var block = new WriteOnceBlock<int> (null);
			var action = new ActionBlock<int> (i =>
			{
				act = i == 42;
				evt.Set ();
			});

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

			block.LinkTo (action);

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

			Assert.IsTrue (act);
		}
Esempio n. 37
0
		public void CloningTest ()
		{
			object act1 = null, act2 = null;
			var evt = new CountdownEvent (2);

			object source = new object ();
			var broadcast = new WriteOnceBlock<object> (o => new object ());
			var action1 = new ActionBlock<object> (i => { act1 = i; evt.Signal (); });
			var action2 = new ActionBlock<object> (i => { act2 = i; evt.Signal (); });

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

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

			evt.Wait ();

			Assert.IsNotNull (act1);
			Assert.IsNotNull (act2);

			Assert.IsFalse (source.Equals (act1));
			Assert.IsFalse (source.Equals (act2));
			Assert.IsFalse (act2.Equals (act1));
		}
Esempio n. 38
0
		public void AsyncReceiveTest ()
		{
			int result = -1;
			var mre = new ManualResetEventSlim (false);

			var block = new WriteOnceBlock<int> (null);
			block.ReceiveAsync ().ContinueWith (i =>
			{
				result = i.Result;
				mre.Set ();
			});
			Task.Factory.StartNew (() =>
			{
				Thread.Sleep (100);
				block.Post (42);
			});
			Assert.IsTrue (mre.Wait (1000));

			Assert.AreEqual (42, result);
		}
Esempio n. 39
0
 public QueryRequest(Query query, WriteOnceBlock<object> responseBlock)
 {
     Response = responseBlock;
     Query = query;
 }
        public async Task TestOutputAvailableAsync_DataAfterCompletion()
        {
            foreach (bool withUncanceledToken in DataflowTestHelpers.BooleanValues)
                foreach (bool withData in DataflowTestHelpers.BooleanValues)
                {
                    var wob = new WriteOnceBlock<int>(_ => _);
                    if (withData)
                        wob.Post(42);
                    else
                        wob.Complete();
                    await wob.Completion;

                    Task<bool> t = withUncanceledToken ?
                        wob.OutputAvailableAsync(new CancellationTokenSource().Token) :
                        wob.OutputAvailableAsync();

                    Assert.Equal(expected: withData, actual: await t);
                }
        }
Esempio n. 41
0
        public async Task TestConsumeToAccept()
        {
            var wob = new WriteOnceBlock<int>(i => i * 2);
            wob.Post(1);
            await wob.Completion;

            var b2 = new BatchedJoinBlock<int, int>(1);
            wob.LinkTo(b2.Target2, new DataflowLinkOptions { PropagateCompletion = true });
            Tuple<IList<int>, IList<int>> item2 = await b2.ReceiveAsync();
            Assert.Equal(expected: 0, actual: item2.Item1.Count);
            Assert.Equal(expected: 1, actual: item2.Item2.Count);
            b2.Target1.Complete();

            var b3 = new BatchedJoinBlock<int, int, int>(1);
            wob.LinkTo(b3.Target3, new DataflowLinkOptions { PropagateCompletion = true });
            Tuple<IList<int>, IList<int>, IList<int>> item3 = await b3.ReceiveAsync();
            Assert.Equal(expected: 0, actual: item3.Item1.Count);
            Assert.Equal(expected: 0, actual: item3.Item2.Count);
            Assert.Equal(expected: 1, actual: item3.Item3.Count);
            b3.Target1.Complete();
            b3.Target2.Complete();

            await Task.WhenAll(b2.Completion, b3.Completion);
        }
Esempio n. 42
0
        public Journalable(object target, WriteOnceBlock<DateTimeOffset> timestampBlock)
        {
            Target = target;

            TimestampBlock = timestampBlock;
        }
Esempio n. 43
0
        public async Task WriteOnceToAction()
        {
            int completedCount = 0;
            var c = new ActionBlock<int>(i => completedCount++);
            var singleAssignments = Enumerable.Range(0, Iterations).Select(_ =>
            {
                var s = new WriteOnceBlock<int>(i => i);
                s.LinkTo(c);
                return s;
            }).ToList();
            var ignored = Task.WhenAll(singleAssignments.Select(s => s.Completion)).ContinueWith(
                _ => c.Complete(), CancellationToken.None, TaskContinuationOptions.None, TaskScheduler.Default);

            foreach (var s in singleAssignments) s.Post(1);

            await c.Completion;
            Assert.Equal(expected: Iterations, actual: completedCount);
        }
Esempio n. 44
0
		public void DontOfferTwiceTest ()
		{
			var scheduler = new TestScheduler ();
			var block = new WriteOnceBlock<int> (null,
				new DataflowBlockOptions { TaskScheduler = scheduler });
			var target =
				new TestTargetBlock<int> { Postpone = true };
			block.LinkTo (target);

			Assert.IsFalse (target.HasPostponed);

			Assert.IsTrue (block.Post (1));

			scheduler.ExecuteAll ();

			Assert.IsTrue (target.HasPostponed);

			target.Postpone = false;

			int value;
			Assert.IsTrue (target.RetryPostponed (out value));
			Assert.AreEqual (1, value);

			block.LinkTo (new BufferBlock<int> ());

			scheduler.ExecuteAll ();

			Assert.AreEqual (default(int), target.DirectlyAccepted);
		}
Esempio n. 45
0
		public void PostponedTest ()
		{
			var block = new WriteOnceBlock<int> (null);
			var target = new BufferBlock<int> (
				new DataflowBlockOptions { BoundedCapacity = 1 });
			block.LinkTo (target);

			Assert.IsTrue (target.Post (1));

			Assert.IsTrue (block.Post (2));

			Assert.AreEqual (1, target.Receive (TimeSpan.FromMilliseconds (100)));
			Assert.AreEqual (2, target.Receive (TimeSpan.FromMilliseconds (100)));
		}
Esempio n. 46
0
		public void TryReceiveBehavior ()
		{
			var block = new WriteOnceBlock<int> (null);
			int foo;
			Assert.IsFalse (block.TryReceive (null, out foo));
			block.Post (42);
			Assert.IsTrue (block.TryReceive (null, out foo));
			Assert.AreEqual (42, foo);
			Assert.IsTrue (block.TryReceive (null, out foo));
			Assert.IsFalse (block.TryReceive (i => i == 0, out foo));
			IList<int> bar;
			Assert.IsTrue (block.TryReceiveAll (out bar));
			Assert.IsNotNull (bar);
			Assert.AreEqual (1, bar.Count);
			Assert.AreEqual (42, bar[0]);
		}
Esempio n. 47
0
 public CommandRequest(Command command, WriteOnceBlock<object> response)
 {
     Command = command;
     Response = response;
 }
Esempio n. 48
0
		public void WriteOnceBehaviorTest ()
		{
			bool act1 = false, act2 = false;
			var evt = new CountdownEvent (2);

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

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

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

			evt.Wait ();

			Assert.IsTrue (act1);
			Assert.IsTrue (act2);

			Assert.IsFalse (broadcast.Post (24));
			Thread.Sleep (1600);

			Assert.IsTrue (act1);
			Assert.IsTrue (act2);
		}
Esempio n. 49
0
		public void AsyncReceiveTestCanceled ()
		{
			var src = new CancellationTokenSource ();

			var block = new WriteOnceBlock<int> (null);
			var task = block.ReceiveAsync (src.Token);
			Task.Factory.StartNew (() =>
			{
				Thread.Sleep (800);
				block.Post (42);
			});
			Thread.Sleep (50);
			src.Cancel ();

			AggregateException ex = null;

			try {
				task.Wait ();
			} catch (AggregateException e) {
				ex = e;
			}

			Assert.IsNotNull (ex);
			Assert.IsNotNull (ex.InnerException);
			Assert.IsInstanceOfType (typeof(OperationCanceledException),
				ex.InnerException);
			Assert.IsTrue (task.IsCompleted);
			Assert.AreEqual (TaskStatus.Canceled, task.Status);
		}
        public void TestStatusAfterComplete()
        {
            bool passed = true;

            var writeOnce = new WriteOnceBlock<int>(x => x);
            writeOnce.Complete();
            try
            {
                writeOnce.Completion.Wait();
                Console.WriteLine("Completed without exception - Passed");
                passed = writeOnce.Completion.Status == TaskStatus.RanToCompletion;
                Console.WriteLine("Status ({0}) - {1}", writeOnce.Completion.Status, passed ? "Passed" : "FAILED");
            }
            catch (AggregateException ae)
            {
                ae.Handle(e => e is TaskCanceledException);
                passed = false;
                Console.WriteLine("Completed without exception - FAILED");
            }

            Assert.True(passed, "Test failed.");
        }
        public void TestCanceledLinking()
        {
            bool passed = true;

            var cts = new CancellationTokenSource();
            cts.Cancel();
            var options = new DataflowBlockOptions { CancellationToken = cts.Token };
            var writeOnce = new WriteOnceBlock<int>(x => x, options);
            var target = new ActionBlock<int>(x => { });
            try
            {
                writeOnce.LinkTo(target);
                Console.WriteLine("Completed without exception - Passed");
            }
            catch (Exception)
            {
                passed = false;
                Console.WriteLine("Completed without exception - FAILED");
            }

            Assert.True(passed, "Test failed.");
        }
        public void TestWriteOnceCloning()
        {
            // Test cloning when a clone function is provided
            {
                var writeOnce = new WriteOnceBlock<int>(x => -x);
                Assert.True(writeOnce.Post(42), "Expected initial post on cloning WriteOnce to succeed");
                Assert.False(writeOnce.Post(43), "Expected secondary post on cloning WriteOnce to fail");
                Assert.True(writeOnce.Receive() == -42, "Expected Receive'd data to be a clone");
                int item;
                Assert.True(writeOnce.TryReceive(out item) && item == -42, "Expected TryReceive'd data to be a clone");
                IList<int> items;
                Assert.True(((IReceivableSourceBlock<int>)writeOnce).TryReceiveAll(out items) && items.Count == 1 && items[0] == -42, "Expected TryReceiveAll'd data to be a clone");
                var ab = new ActionBlock<int>(i =>
                {
                    Assert.True(i == -42, "Expected propagated data to be a clone.");
                });
                writeOnce.LinkTo(ab);
                ab.Complete();
                Assert.True(ab.Completion.Wait(4000), "Expected action block to complete after cloned data flowed to it");
            }

            // Test successful processing when no clone function exists
            {
                var data = new object();
                var writeOnce = new WriteOnceBlock<object>(null);
                Assert.True(writeOnce.Post(data), "Expected initial post on non-cloning WriteOnce to succeed");
                Assert.False(writeOnce.Post(new object()), "Expected secondary post on non-cloning WriteOnce to fail");
                Assert.True(writeOnce.Receive() == data, "Expected Receive'd data to be original data");
                object item;
                Assert.True(writeOnce.TryReceive(out item) && item == data, "Expected TryReceive'd data to be original data");
                IList<object> items;
                Assert.True(((IReceivableSourceBlock<object>)writeOnce).TryReceiveAll(out items) && items.Count == 1 && items[0] == data, "Expected TryReceiveAll'd data to be original data");
                var ab = new ActionBlock<object>(i =>
                {
                    Assert.True(i == data, "Expected propagated data to be original data.");
                });
                writeOnce.LinkTo(ab);
                ab.Complete();
                Assert.True(ab.Completion.Wait(4000), "Expected action block to complete after original data flowed to it");
            }
        }
Esempio n. 53
0
        internal static bool WriteOnceToAction()
        {
            const int ITERS = 2;
            int completedCount = 0;
            var c = new ActionBlock<int>(i => completedCount++);
            var singleAssignments = Enumerable.Range(0, ITERS).Select(_ =>
            {
                var s = new WriteOnceBlock<int>(i => i);
                s.LinkTo(c);
                return s;
            }).ToList();
            Task.Factory.ContinueWhenAll(singleAssignments.Select(s => s.Completion).ToArray(), _ => c.Complete());

            foreach (var s in singleAssignments) s.Post(1);
            c.Completion.Wait();

            return completedCount == ITERS;
        }
Esempio n. 54
0
		public void TryReceiveBehaviorTest ()
		{
			var block = new WriteOnceBlock<int> (null);
			int foo;
			Assert.IsFalse (block.TryReceive (null, out foo));
			block.Post (42);
			Assert.IsTrue (block.TryReceive (null, out foo));
			Assert.AreEqual (42, foo);
			Assert.IsTrue (block.TryReceive (null, out foo));
			Assert.IsFalse (block.TryReceive (i => i == 0, out foo));
			IList<int> bar;
			Assert.IsTrue (((IReceivableSourceBlock<int>)block).TryReceiveAll (out bar));
			CollectionAssert.AreEqual (new[] { 42 }, bar);
		}
Esempio n. 55
0
 public async Task TestFaultyScheduler()
 {
     var wob = new WriteOnceBlock<int>(null, new DataflowBlockOptions {
         TaskScheduler = new DelegateTaskScheduler {
             QueueTaskDelegate = delegate {
                 throw new InvalidCastException();
             }
         }
     });
     wob.LinkTo(DataflowBlock.NullTarget<int>());
     wob.Post(42);
     await Assert.ThrowsAsync<TaskSchedulerException>(() => wob.Completion);
 }
Esempio n. 56
0
		public void QueuedMessageTest ()
		{
			var scheduler = new TestScheduler ();
			var block = new WriteOnceBlock<int> (null,
				new DataflowBlockOptions { TaskScheduler = scheduler });
			var target = new BufferBlock<int> ();
			block.LinkTo (target);

			Assert.IsTrue (block.Post (1));

			AssertEx.Throws<TimeoutException> (
				() => target.Receive (TimeSpan.FromMilliseconds (100)));

			scheduler.ExecuteAll ();

			int item;
			Assert.IsTrue (target.TryReceive (out item));
			Assert.AreEqual (1, item);
		}
        public async Task TestAsObservableAndAsObserver_DataPropagation()
        {
            // Test that preset data flows correctly
            {
                var bb = new BufferBlock<int>();
                bb.PostRange(0, 2);
                bb.Complete();

                int nextValueExpected = 0;
                var ab = new ActionBlock<int>(i => {
                    Assert.True(i == nextValueExpected, string.Format("Expected next value to be {0} but got {1}", nextValueExpected, i));
                    nextValueExpected++;
                });

                bb.AsObservable().Subscribe(ab.AsObserver());
                await ab.Completion;
            }

            // Test that new data flows correctly
            {
                int nextValueExpected = -2;
                var ab = new ActionBlock<int>(i => {
                    Assert.True(i == nextValueExpected, string.Format("Expected next value to be {0} but got {1}", nextValueExpected, i));
                    nextValueExpected++;
                });

                var bb = new BufferBlock<int>();
                bb.AsObservable().Subscribe(ab.AsObserver());

                bb.PostRange(-2, 0);
                bb.Complete();

                await ab.Completion;
            }

            // Test that unsubscribing stops flow of data and stops completion
            {
                var target = new BufferBlock<int>();
                var source = new BufferBlock<int>();

                using (source.AsObservable().Subscribe(target.AsObserver()))
                {
                    source.PostItems(1, 2);
                    Assert.Equal(expected: 1, actual: await target.ReceiveAsync());
                    Assert.Equal(expected: 2, actual: await target.ReceiveAsync());
                }

                source.Post(3);
                var wb = new WriteOnceBlock<int>(i => i);
                source.LinkTo(wb);
                await wb.Completion;

                source.Complete();
                await source.Completion;

                Assert.False(target.Completion.IsCompleted);
            }
        }
        public void RunWriteOnceBlockConformanceTests()
        {
            bool passed = true, localPassed = true;
            {
                // Test posting then receiving
                localPassed = true;
                var wob = new WriteOnceBlock<int>(i => i);
                int successfulPosts = 0;
                for (int i = 10; i <= 20; i++)
                {
                    successfulPosts += wob.Post(i) ? 1 : 0;
                }
                localPassed |= successfulPosts == 1;
                localPassed |= wob.Receive() == 10;
                Console.WriteLine("{0}: Posting then receiving", localPassed ? "Success" : "Failure");
                passed &= localPassed;
            }

            {
                // Test receiving then posting
                localPassed = true;
                var wob = new WriteOnceBlock<int>(i => i);
                Task.Factory.StartNew(() =>
                {
                    Task.Delay(1000).Wait();
                    wob.Post(42);
                });
                localPassed |= wob.Receive() == 42;
                localPassed |= wob.Post(43) == false;
                wob.Completion.Wait();
                Console.WriteLine("{0}: Receiving then posting", localPassed ? "Success" : "Failure");
                passed &= localPassed;
            }

            {
                // Test broadcasting
                localPassed = true;
                var wob = new WriteOnceBlock<int>(i => i + 1);
                var tb1 = new TransformBlock<int, int>(i => i);
                var tb2 = new TransformBlock<int, int>(i => i);
                var tb3 = new TransformBlock<int, int>(i => i);
                wob.LinkTo(tb1);
                wob.LinkTo(tb2);
                wob.LinkTo(tb3);
                wob.Post(42);
                localPassed |= tb1.Receive() == 43;
                localPassed |= tb2.Receive() == 43;
                localPassed |= tb3.Receive() == 43;
                Console.WriteLine("{0}: Broadcasting", localPassed ? "Success" : "Failure");
                passed &= localPassed;
            }

            {
                // Test using a precanceled token
                localPassed = true;
                try
                {
                    var cts = new CancellationTokenSource();
                    cts.Cancel();
                    var dbo = new DataflowBlockOptions { CancellationToken = cts.Token };
                    var wob = new WriteOnceBlock<int>(i => i, dbo);

                    int ignoredValue;
                    IList<int> ignoredValues;
                    localPassed &= wob.LinkTo(new ActionBlock<int>(delegate { })) != null;
                    localPassed &= wob.SendAsync(42).Result == false;
                    localPassed &= ((IReceivableSourceBlock<int>)wob).TryReceiveAll(out ignoredValues) == false;
                    localPassed &= wob.Post(42) == false;
                    localPassed &= wob.TryReceive(out ignoredValue) == false;
                    localPassed &= wob.Completion != null;
                    wob.Complete();
                }
                catch (Exception)
                {
                    localPassed = false;
                }
                Console.WriteLine("{0}: Precanceled tokens work correctly", localPassed ? "Success" : "Failure");
                passed &= localPassed;
            }

            {
                // Test using token canceled after construction
                localPassed = true;
                try
                {
                    var cts = new CancellationTokenSource();
                    var dbo = new DataflowBlockOptions { CancellationToken = cts.Token };
                    var wob = new WriteOnceBlock<int>(i => i, dbo);
                    cts.Cancel();

                    int ignoredValue;
                    IList<int> ignoredValues;
                    localPassed &= wob.LinkTo(new ActionBlock<int>(delegate { })) != null;
                    localPassed &= wob.SendAsync(42).Result == false;
                    localPassed &= ((IReceivableSourceBlock<int>)wob).TryReceiveAll(out ignoredValues) == false;
                    localPassed &= wob.Post(42) == false;
                    localPassed &= wob.TryReceive(out ignoredValue) == false;
                    localPassed &= wob.Completion != null;
                    wob.Complete();
                }
                catch (Exception)
                {
                    localPassed = false;
                }
                Console.WriteLine("{0}: Precanceled tokens work correctly", localPassed ? "Success" : "Failure");
                passed &= localPassed;
            }

            Assert.True(passed, "Test failed.");
        }
Esempio n. 59
0
        public async Task TestReserveReleaseConsume()
        {
            var wb = new WriteOnceBlock<int>(i => i * 2);
            wb.Post(1);
            await DataflowTestHelpers.TestReserveAndRelease(wb, reservationIsTargetSpecific: false);

            wb = new WriteOnceBlock<int>(i => i * 2);
            wb.Post(2);
            await DataflowTestHelpers.TestReserveAndConsume(wb, reservationIsTargetSpecific: false);
        }
Esempio n. 60
0
 public async Task TestFaultyTarget()
 {
     var wob = new WriteOnceBlock<int>(null);
     wob.LinkTo(new DelegatePropagator<int, int> {
         OfferMessageDelegate = delegate {
             throw new FormatException();
         }
     });
     wob.Post(42);
     await Assert.ThrowsAsync<FormatException>(() => wob.Completion);
 }