5 // Jérémie "garuma" Laval <jeremie.laval@gmail.com>
6 // Petr Onderka <gsvick@gmail.com>
8 // Copyright (c) 2011 Jérémie "garuma" Laval
9 // Copyright (c) 2012 Petr Onderka
11 // Permission is hereby granted, free of charge, to any person obtaining a copy
12 // of this software and associated documentation files (the "Software"), to deal
13 // in the Software without restriction, including without limitation the rights
14 // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
15 // copies of the Software, and to permit persons to whom the Software is
16 // furnished to do so, subject to the following conditions:
18 // The above copyright notice and this permission notice shall be included in
19 // all copies or substantial portions of the Software.
21 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
22 // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
23 // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
24 // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
25 // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
26 // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
30 using System.Threading;
31 using System.Threading.Tasks.Dataflow;
32 using NUnit.Framework;
34 namespace MonoTests.System.Threading.Tasks.Dataflow {
36 public class BufferBlockTest {
38 public void BasicUsageTest ()
41 var evt = new ManualResetEventSlim (false);
42 var buffer = new BufferBlock<int> ();
43 var action = new ActionBlock<int> (i =>
48 buffer.LinkTo (action);
50 Assert.IsTrue (buffer.Post (42));
52 Assert.AreEqual (42, data);
56 public void LateBindingTest ()
58 var buffer = new BufferBlock<int> ();
59 var evt = new CountdownEvent (10);
61 for (int i = 0; i < 10; i++)
62 Assert.IsTrue (buffer.Post (i));
64 var block = new ActionBlock<int> (i => evt.Signal ());
65 buffer.LinkTo (block);
71 public void MultipleBindingTest ()
73 var buffer = new BufferBlock<int> ();
74 var evt = new CountdownEvent (10);
78 var block = new ActionBlock<int> (i =>
80 Interlocked.Decrement (ref count);
83 IDisposable bridge = buffer.LinkTo (block);
84 for (int i = 0; i < 10; i++)
85 Assert.IsTrue (buffer.Post (i));
88 Assert.AreEqual (-10, count);
93 var block2 = new ActionBlock<int> (i =>
95 Interlocked.Increment (ref count);
98 buffer.LinkTo (block2);
99 for (int i = 0; i < 10; i++)
100 Assert.IsTrue (buffer.Post (i));
103 Assert.AreEqual (10, count);
107 public void ConsumeToAcceptTest ()
109 var source = new TestSourceBlock<int> ();
110 var buffer = new BufferBlock<int> ();
111 var target = (ITargetBlock<int>)buffer;
113 var header = new DataflowMessageHeader (1);
114 source.AddMessage (header, 1);
116 Assert.AreEqual (DataflowMessageStatus.Accepted,
117 target.OfferMessage (header, 1, source, true));
119 Assert.IsTrue (source.WasConsumed (header));
120 Assert.IsFalse (source.WasReserved (header));