Beispiel #1
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));
        }
		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 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 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);
        }
Beispiel #5
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());
        }
Beispiel #6
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.
             */
        }
Beispiel #7
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;
     }
 }
        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);
        }
Beispiel #9
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);
            }
        }
Beispiel #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();
        }
        private async Task ConnectionReceivedAsync(object sender, EventArgsT <ReadOnlyMemory <byte> > e)
        {
            var r = new Request(e.Value);

            switch (r.Type)
            {
            case RequestType.Cmd:
                _cmdReq.Post(r.Body.ToArray());
                break;

            case RequestType.Buffer:
                await _streamPipe.OutputStream.ComWriteAsync(r.Body);

                break;

            case RequestType.BufferEnd:
                await _streamPipe.OutputStream.ComWriteAsync(r.Body);

                await _streamPipe.Output.CompleteAsync();

                break;

            case RequestType.Cancel:
                _cts.Cancel();
                break;

            default:
                throw new ArgumentOutOfRangeException();
            }
        }
        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!");
        }
Beispiel #13
0
        private static WriteOnceBlock <int> ConstructWriteOnce()
        {
            var block = new WriteOnceBlock <int>(i => i);

            block.Post(0);
            return(block);
        }
Beispiel #14
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));
        }
Beispiel #15
0
        private static void DataStructure_WriteOnceBlock()
        {
            // 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());
        }
        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 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));
        }
Beispiel #18
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();
        }
        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 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);
        }
Beispiel #21
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);
        }
 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;
 }
Beispiel #23
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);
        }
Beispiel #24
0
 public static void TestSync()
 {
     bb.LinkTo(displayBlock);
     bb.LinkTo(saveBlock);
     bb.LinkTo(sendBlock);
     for (int i = 0; i < 4; i++)
     {
         bb.Post(i);
     }
     Console.WriteLine("Post finished");
 }
Beispiel #25
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);
        }
Beispiel #26
0
        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");
            }
        }
Beispiel #27
0
        public static void Run()
        {
            // Create a WriteOnceBlock<string> object.
            // Provides a buffer for receiving and storing at most one element in a network of dataflow blocks
            WriteOnceBlock <string> 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.
            // Executes each of the provided actions, possibly in parallel
            Parallel.Invoke(
                () => writeOnceBlock.Post("Message 1. ThreadId: " + Thread.CurrentThread.ManagedThreadId),
                () => writeOnceBlock.Post("Message 2. ThreadId: " + Thread.CurrentThread.ManagedThreadId),
                () => writeOnceBlock.Post("Message 3. ThreadId: " + Thread.CurrentThread.ManagedThreadId));

            // Receive the message from the block.
            for (int i = 0; i < 5; i++)
            {
                Console.WriteLine(writeOnceBlock.Receive());
            }
        }
Beispiel #28
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);
        }
Beispiel #29
0
        static void ShowWriteOnceBlock()
        {
            // <snippet3>
            // 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
             */
            // </snippet3>
        }
Beispiel #30
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(600); block.Post(42); });
            mre.Wait();

            Assert.AreEqual(42, result);
        }
Beispiel #31
0
    public async Task TestWriteOnceBlock()
    {
        var writeOnceBlockTest = new WriteOnceBlock <int>(i => i);
        var queueBlockTest     = new BufferBlock <string>();
        var transformBlockTest = new TransformBlock <string, Tuple <int, string> >(async str => Tuple.Create(await writeOnceBlockTest.ReceiveAsync(), str));
        var actionBlockTest    = new ActionBlock <Tuple <int, string> >(tuple => Console.WriteLine($"I received int {tuple.Item1} and string {tuple.Item2}."));

        queueBlockTest.LinkTo(transformBlockTest, new DataflowLinkOptions {
            PropagateCompletion = true
        });
        transformBlockTest.LinkTo(actionBlockTest, new DataflowLinkOptions {
            PropagateCompletion = true
        });
        writeOnceBlockTest.Post(3);
        queueBlockTest.Post("String1");
        queueBlockTest.Post("String2");
        writeOnceBlockTest.Post(4);
        writeOnceBlockTest.Post(5);
        queueBlockTest.Post("String3");
        queueBlockTest.Post("String4");
        queueBlockTest.Complete();
        await actionBlockTest.Completion;
    }
Beispiel #32
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);
        }
Beispiel #33
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);
		}
Beispiel #34
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));
		}
        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);
        }
 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);
 }
        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.");
        }
Beispiel #38
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]);
		}
        public async Task TestPostThenReceive()
        {
            var wob = new WriteOnceBlock<int>(i => i);
            for (int i = 10; i < 15; i++)
            {
                bool posted = wob.Post(i);
                Assert.Equal(expected: i == 10, actual: posted);
            }
            int item;
            Assert.True(wob.TryReceive(out item));
            Assert.Equal(expected: 10, actual: item);
            await wob.Completion;

            wob = new WriteOnceBlock<int>(null);
            wob.Post(42);
            Task<int> t = wob.ReceiveAsync();
            Assert.True(t.IsCompleted);
            Assert.Equal(expected: 42, actual: t.Result);
            await wob.Completion;
        }
 public async Task TestBroadcasting()
 {
     var wob = new WriteOnceBlock<int>(i => i + 1);
     var targets = Enumerable.Range(0, 3).Select(_ => new TransformBlock<int, int>(i => i)).ToArray();
     foreach (var target in targets)
     {
         wob.LinkTo(target);
     }
     wob.Post(42);
     foreach (var target in targets)
     {
         Assert.Equal(expected: 43, actual: await target.ReceiveAsync());
     }
 }
Beispiel #41
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);
		}
Beispiel #42
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);
		}
Beispiel #43
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);
		}
Beispiel #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);
		}
Beispiel #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)));
		}
        public async Task TestCloning()
        {
            // Test cloning when a clone function is provided
            {
                int data = 42;
                var wob = new WriteOnceBlock<int>(x => -x);
                Assert.True(wob.Post(data));

                Assert.False(wob.Post(data + 1));

                for (int i = 0; i < 3; i++)
                {
                    int item;
                    Assert.True(wob.TryReceive(out item));
                    Assert.Equal(expected: -data, actual: item);

                    Assert.Equal(expected: -data, actual: wob.Receive());

                    Assert.Equal(expected: -data, actual: await wob.ReceiveAsync());

                    IList<int> items;
                    Assert.True(((IReceivableSourceBlock<int>)wob).TryReceiveAll(out items));
                    Assert.Equal(expected: items.Count, actual: 1);
                    Assert.Equal(expected: -data, actual: items[0]);
                }

                int result = 0;
                var target = new ActionBlock<int>(i => {
                    Assert.Equal(expected: 0, actual: result);
                    result = i;
                    Assert.Equal(expected: -data, actual: i);
                });
                wob.LinkTo(target, new DataflowLinkOptions { PropagateCompletion = true });
                await target.Completion;
            }

            // Test successful processing when no clone function exists
            {
                var data = new object();
                var wob = new WriteOnceBlock<object>(null);
                Assert.True(wob.Post(data));

                Assert.False(wob.Post(new object()));

                object result;
                for (int i = 0; i < 3; i++)
                {
                    Assert.True(wob.TryReceive(out result));
                    Assert.Equal(expected: data, actual: result);

                    Assert.Equal(expected: data, actual: wob.Receive());
                    Assert.Equal(expected: data, actual: await wob.ReceiveAsync());

                    IList<object> items;
                    Assert.True(((IReceivableSourceBlock<object>)wob).TryReceiveAll(out items));
                    Assert.Equal(expected: 1, actual: items.Count);
                    Assert.Equal(expected: data, actual: items[0]);
                }

                result = null;
                var target = new ActionBlock<object>(o => {
                    Assert.Null(result);
                    result = o;
                    Assert.Equal(expected: data, actual: o);
                });
                wob.LinkTo(target, new DataflowLinkOptions { PropagateCompletion = true });
                await target.Completion;
            }
        }
        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);
            }
        }
Beispiel #48
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 async Task TestTryReceiveWithFilter()
        {
            var wob = new WriteOnceBlock<int>(null);
            wob.Post(1);

            int item;
            Assert.True(wob.TryReceive(out item));
            Assert.Equal(expected: 1, actual: item);

            Assert.True(wob.TryReceive(i => i == 1, out item));
            Assert.Equal(expected: 1, actual: item);

            Assert.False(wob.TryReceive(i => i == 0, out item));

            await wob.Completion;
        }
        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);
        }
        public async Task TestReceiveThenPost()
        {
            var wob = new WriteOnceBlock<int>(null);
            var ignored = Task.Run(() => wob.Post(42));
            Assert.Equal(expected: 42, actual: wob.Receive()); // this should always pass, but due to race we may not test what we're hoping to
            await wob.Completion;

            wob = new WriteOnceBlock<int>(null);
            Task<int> t = wob.ReceiveAsync();
            Assert.False(t.IsCompleted);
            wob.Post(16);
            Assert.Equal(expected: 16, actual: await t);
        }
        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");
            }
        }
 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);
 }
 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;
     }
 }
        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);
                }
        }
Beispiel #56
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);
		}