本文整理汇总了C#中BufferBlock.TryReceive方法的典型用法代码示例。如果您正苦于以下问题:C# BufferBlock.TryReceive方法的具体用法?C# BufferBlock.TryReceive怎么用?C# BufferBlock.TryReceive使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类BufferBlock
的用法示例。
在下文中一共展示了BufferBlock.TryReceive方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: GreedyJoin3Test
public void GreedyJoin3Test ()
{
var scheduler = new TestScheduler ();
var block =
new JoinBlock<int, int, int> (new GroupingDataflowBlockOptions
{ TaskScheduler = scheduler });
var source1 =
new BufferBlock<int> (new DataflowBlockOptions { TaskScheduler = scheduler });
var source2 =
new BufferBlock<int> (new DataflowBlockOptions { TaskScheduler = scheduler });
var source3 =
new BufferBlock<int> (new DataflowBlockOptions { TaskScheduler = scheduler });
Assert.IsNotNull (source1.LinkTo (block.Target1));
Assert.IsNotNull (source2.LinkTo (block.Target2));
Assert.IsNotNull (source3.LinkTo (block.Target3));
Assert.IsTrue (source1.Post (1));
scheduler.ExecuteAll ();
int i;
Assert.IsFalse (source1.TryReceive (out i));
Assert.IsTrue (source2.Post (11));
Assert.IsTrue (source3.Post (21));
scheduler.ExecuteAll ();
Assert.IsFalse (source2.TryReceive (out i));
Assert.IsFalse (source3.TryReceive (out i));
Tuple<int, int, int> tuple;
Assert.IsTrue (block.TryReceive (out tuple));
Assert.AreEqual (Tuple.Create (1, 11, 21), tuple);
}
示例2: TryReceiveTest
public void TryReceiveTest ()
{
var block = new BufferBlock<int> ();
int value = -1;
block.Post (42);
Thread.Sleep (500);
Assert.IsTrue (block.TryReceive (out value));
Assert.AreEqual (42, value);
}
示例3: OnlyOneConsumedTest
public void OnlyOneConsumedTest ()
{
var source1 = new BufferBlock<int> ();
var source2 = new BufferBlock<long> ();
int action1 = 0;
int action2 = 0;
var completion = DataflowBlock.Choose (
source1, _ => action1++,
source2, _ => action2++);
source1.Post (42);
source1.Post (43);
Assert.IsTrue (completion.Wait (1000));
Assert.AreEqual (0, completion.Result);
Assert.AreEqual (1, action1);
Assert.AreEqual (0, action2);
int item;
Assert.IsTrue (source1.TryReceive (out item));
Assert.AreEqual (43, item);
}
示例4: MaxMessagesBroadcastTest
public void MaxMessagesBroadcastTest ()
{
var scheduler = new TestScheduler ();
var source = new BroadcastBlock<int> (
null, new DataflowBlockOptions { TaskScheduler = scheduler });
var target = new BufferBlock<int>(
new DataflowBlockOptions { TaskScheduler = scheduler, BoundedCapacity = 1 });
Assert.IsNotNull (
source.LinkTo (target, new DataflowLinkOptions { MaxMessages = 2 }));
// should be accepted
Assert.IsTrue (source.Post (42));
scheduler.ExecuteAll ();
// should be postponed, but counted into the limit
Assert.IsTrue (source.Post (43));
scheduler.ExecuteAll ();
// shouldn't be even offered for now
Assert.IsTrue (source.Post (44));
scheduler.ExecuteAll ();
int item;
Assert.IsTrue (target.TryReceive (out item));
Assert.AreEqual (42, item);
scheduler.ExecuteAll ();
Assert.IsTrue (target.TryReceive (out item));
Assert.AreEqual (44, item);
}
示例5: NonGreedyBatchWithBoundedCapacityTriggerTest2
public void NonGreedyBatchWithBoundedCapacityTriggerTest2 ()
{
var scheduler = new TestScheduler ();
var block = new BatchBlock<int> (3,
new GroupingDataflowBlockOptions
{ Greedy = false, BoundedCapacity = 3, TaskScheduler = scheduler });
var source1 =
new BufferBlock<int> (new DataflowBlockOptions { TaskScheduler = scheduler });
var source2 =
new BufferBlock<int> (new DataflowBlockOptions { TaskScheduler = scheduler });
Assert.IsNotNull (source1.LinkTo (block));
Assert.IsNotNull (source2.LinkTo (block));
// trigger 2, then trigger another 2 and then trigger 2 once more
// while havaing capacity of 3
Assert.IsTrue (source1.Post (11));
Assert.IsTrue (source2.Post (21));
block.TriggerBatch ();
scheduler.ExecuteAll ();
Assert.IsTrue (source1.Post (12));
Assert.IsTrue (source2.Post (22));
block.TriggerBatch ();
scheduler.ExecuteAll ();
Assert.IsTrue (source1.Post (13));
Assert.IsTrue (source2.Post (23));
block.TriggerBatch ();
scheduler.ExecuteAll ();
int i;
Assert.IsTrue (source1.TryReceive (out i));
Assert.AreEqual (13, i);
Assert.IsTrue (source2.TryReceive (out i));
Assert.AreEqual (23, i);
int[] batch;
Assert.IsTrue (block.TryReceive (out batch));
CollectionAssert.AreEquivalent (new[] { 11, 21 }, batch);
Assert.IsTrue (block.TryReceive (out batch));
CollectionAssert.AreEquivalent (new[] { 12, 22 }, batch);
Assert.IsFalse (block.TryReceive (out batch));
}
示例6: MaxMessagesPostponedUnconsumedTest
public void MaxMessagesPostponedUnconsumedTest ()
{
var scheduler = new TestScheduler ();
var source =
new BufferBlock<int> (new DataflowBlockOptions { TaskScheduler = scheduler });
var target =
new BufferBlock<int> (
new DataflowBlockOptions { TaskScheduler = scheduler, BoundedCapacity = 1 });
Assert.IsNotNull (
source.LinkTo (target, new DataflowLinkOptions { MaxMessages = 2 }));
Assert.IsTrue (source.Post (42));
Assert.IsTrue (source.Post (43));
Assert.IsTrue (source.Post (44));
Assert.IsTrue (source.Post (45));
scheduler.ExecuteAll ();
int item;
Assert.IsTrue (source.TryReceive (null, out item));
Assert.AreEqual (43, item);
Assert.IsTrue (target.TryReceive (null, out item));
Assert.AreEqual (42, item);
Assert.IsFalse (target.TryReceive (null, out item));
scheduler.ExecuteAll ();
Assert.IsTrue (target.TryReceive (null, out item));
Assert.AreEqual (44, item);
scheduler.ExecuteAll ();
Assert.IsFalse (target.TryReceive (null, out item));
Assert.IsTrue (source.TryReceive (null, out item));
Assert.AreEqual (45, item);
}
示例7: GetFileWordSaverBlock
public static IPropagatorBlock<FileWord, FileWord> GetFileWordSaverBlock(Func<IRepository> repositoryFactory)
{
var inputBuffer = new BufferBlock<FileWord>();
var outputBuffer = new BufferBlock<FileWord>();
var batchBlockWithoutParents = new BatchBlock<FileWord>(1000);
inputBuffer.LinkTo(batchBlockWithoutParents, i => i.File.FileId > 0 && i.Word.WordId > 0);
inputBuffer.PropagateCompleted(batchBlockWithoutParents);
var saveWithoutParentsBlock = new TransformManyBlock<FileWord[], FileWord>(
async fileWords =>
{
return await SaveEntities(repositoryFactory, fileWords, true);
},
new ExecutionDataflowBlockOptions
{
MaxDegreeOfParallelism = Utils.GlobalMaxDegreeOfParallelism
});
batchBlockWithoutParents.LinkToAndPropagateCompleted(saveWithoutParentsBlock);
saveWithoutParentsBlock.LinkTo(outputBuffer);
var batchBlockWithParents = new BatchBlock<FileWord>(300);
// MaxMessages value means inputBuffer will unlink automatically from batchBlockWithParents after 300 messages.
// This is required to prohibit "stealing" of workload from saveWithoutParentsBlock
inputBuffer.LinkTo(batchBlockWithParents, new DataflowLinkOptions { MaxMessages = 300 });
inputBuffer.PropagateCompleted(batchBlockWithParents);
var saveWithParentsBlock = new TransformManyBlock<FileWord[], FileWord>(
async fileWords =>
{
var res = await SaveEntities(repositoryFactory, fileWords, false);
FileWord fileWord;
if (inputBuffer.TryReceive(out fileWord)) // This unblocks inputBuffer due to unlinking from batchBlockWithParents
{
if (fileWord.File.FileId > 0 && fileWord.Word.WordId > 0)
{
batchBlockWithoutParents.Post(fileWord);
}
else
{
batchBlockWithParents.Post(fileWord);
}
}
// Link again for another 300 messages
inputBuffer.LinkTo(batchBlockWithParents, new DataflowLinkOptions { MaxMessages = 300 });
return res;
},
new ExecutionDataflowBlockOptions
{
MaxDegreeOfParallelism = 1 // If we are saving files/words also we cannot do this concurrently or duplicates of files/words may be inserted
});
batchBlockWithParents.LinkToAndPropagateCompleted(saveWithParentsBlock);
saveWithParentsBlock.LinkTo(outputBuffer);
saveWithoutParentsBlock.Completion.ContinueWith(
t => ((IDataflowBlock)outputBuffer).Fault(t.Exception),
TaskContinuationOptions.OnlyOnFaulted);
saveWithParentsBlock.Completion.ContinueWith(
t => ((IDataflowBlock)outputBuffer).Fault(t.Exception),
TaskContinuationOptions.OnlyOnFaulted);
Task.WhenAll(saveWithoutParentsBlock.Completion, saveWithParentsBlock.Completion)
.ContinueWith(t => outputBuffer.Complete(), TaskContinuationOptions.NotOnFaulted);
return DataflowBlock.Encapsulate(inputBuffer, outputBuffer);
}
示例8: NonGreedyBatchWithBoundedCapacityTest
public void NonGreedyBatchWithBoundedCapacityTest ()
{
var scheduler = new TestScheduler ();
var block = new BatchBlock<int> (2,
new GroupingDataflowBlockOptions
{ Greedy = false, BoundedCapacity = 2, TaskScheduler = scheduler });
var source1 =
new BufferBlock<int> (new DataflowBlockOptions { TaskScheduler = scheduler });
var source2 =
new BufferBlock<int> (new DataflowBlockOptions { TaskScheduler = scheduler });
Assert.IsNotNull (source1.LinkTo (block));
Assert.IsNotNull (source2.LinkTo (block));
Assert.IsTrue (source1.Post (11));
Assert.IsTrue (source2.Post (21));
scheduler.ExecuteAll ();
Assert.IsTrue (source1.Post (12));
Assert.IsTrue (source2.Post (22));
scheduler.ExecuteAll ();
int i;
Assert.IsTrue (source1.TryReceive (out i));
Assert.AreEqual (12, i);
Assert.IsTrue (source1.Post (13));
int[] batch;
Assert.IsTrue (block.TryReceive (out batch));
CollectionAssert.AreEquivalent (new[] { 11, 21 }, batch);
scheduler.ExecuteAll ();
Assert.IsTrue (block.TryReceive (out batch));
CollectionAssert.AreEquivalent (new[] { 13, 22 }, batch);
}
示例9: LinkToPredicateClonerTest
public void LinkToPredicateClonerTest ()
{
var scheduler = new TestScheduler ();
var source = new BroadcastBlock<int> (i => i * 10,
new DataflowBlockOptions { TaskScheduler = scheduler });
var target = new BufferBlock<int> ();
source.LinkTo (target, i => i < 10);
Assert.IsTrue (source.Post (1));
scheduler.ExecuteAll ();
int item;
Assert.IsTrue (target.TryReceive (out item));
Assert.AreEqual (10, item);
}
示例10: TestReceives
public void TestReceives()
{
for (int test = 0; test < 3; test++)
{
var bb = new BufferBlock<int>();
bb.PostRange(0, 5);
int item;
switch (test)
{
case 0:
IList<int> items;
Assert.True(bb.TryReceiveAll(out items));
Assert.Equal(expected: 5, actual: items.Count);
for (int i = 0; i < items.Count; i++)
{
Assert.Equal(expected: i, actual: items[i]);
}
Assert.False(bb.TryReceiveAll(out items));
break;
case 1:
for (int i = 0; i < 5; i++)
{
Assert.True(bb.TryReceive(f => true, out item));
Assert.Equal(expected: i, actual: item);
}
Assert.False(bb.TryReceive(f => true, out item));
break;
case 2:
for (int i = 0; i < 5; i++)
{
Assert.False(bb.TryReceive(f => f == i + 1, out item));
Assert.True(bb.TryReceive(f => f == i, out item));
Assert.Equal(expected: i, actual: item);
}
Assert.False(bb.TryReceive(f => true, out item));
break;
}
}
}
示例11: RaceTest
public void RaceTest ()
{
var source1 = new BufferBlock<int> ();
var source2 = new BufferBlock<int> ();
int action1 = 0;
int action2 = 0;
var completion = DataflowBlock.Choose (
source1, _ => action1++,
source2, _ => action2++);
var barrier = new Barrier (2);
var t1 = Task.Run (() =>
{
barrier.SignalAndWait ();
source1.Post (10);
});
var t2 = Task.Run (() =>
{
barrier.SignalAndWait ();
source2.Post (20);
});
Task.WaitAll (t1, t2);
Assert.IsTrue (completion.Wait (1000));
Assert.AreEqual (1, action1 + action2);
int item;
Assert.IsTrue (source1.TryReceive (out item) || source2.TryReceive (out item));
}
示例12: TestBufferBlockBounding
public void TestBufferBlockBounding()
{
const int WAIT_TIMEOUT = 4000; // wait at most 4 seconds for a particularly race-condition
// Test buffer doesn't exceed limit
{
bool localPassed = true;
for (int boundedCapacity = 1; boundedCapacity <= 3 && localPassed; boundedCapacity += 2)
{
var b = new BufferBlock<int>(new DataflowBlockOptions { BoundedCapacity = boundedCapacity });
for (int i = 0; i < boundedCapacity; i++)
{
var send = b.SendAsync(i);
Assert.True(send.Wait(0) && send.Result, "Send should succeed as capacity not yet reached");
}
for (int i = boundedCapacity; i < boundedCapacity + 2 && localPassed; i++)
{
Assert.True(b.Count == boundedCapacity, "Count should equal bounded capacity after all posts completed");
var t = b.SendAsync(i);
Assert.True(!t.IsCompleted, "Send should not have completed on a full buffer");
b.Receive();
Assert.True(t.Wait(WAIT_TIMEOUT), "The send should have completed before the timeout");
Assert.True(t.IsCompleted && t.Result, "The send should have completed successfully");
Assert.True(SpinWait.SpinUntil(() => b.Count == boundedCapacity, WAIT_TIMEOUT), "The count should be back at the bounded capacity after successful send");
}
int remainingCount = b.Count;
while (b.Count > 0)
{
remainingCount--;
int ignored;
Assert.True(b.TryReceive(out ignored), "Should have been able to successfully remove each item");
}
Assert.True(remainingCount == 0, "Should be no items left after removals");
}
Assert.True(localPassed, string.Format("{0}: Doesn't exceed limits", localPassed ? "Success" : "Failure"));
}
// Test correct ordering
{
bool localPassed = true;
for (int boundedCapacity = 1; boundedCapacity <= 3 && localPassed; boundedCapacity += 2)
{
int iters = boundedCapacity + 2;
var tasks = new Task<bool>[iters];
var b = new BufferBlock<int>(new DataflowBlockOptions { BoundedCapacity = boundedCapacity });
for (int i = 0; i < boundedCapacity; i++)
{
var t = b.SendAsync(i);
Assert.True(t.IsCompleted && t.Result, "Sends until capacity reached should complete immediately and successfully");
tasks[i] = t;
}
for (int i = boundedCapacity; i < iters; i++)
{
var t = b.SendAsync(i);
Assert.True(!t.IsCompleted, "Sends after capacity reached should not be completed");
tasks[i] = t;
}
for (int i = 0; i < iters && localPassed; i++)
{
if (i >= boundedCapacity & i < iters - boundedCapacity)
{
Assert.True(!tasks[i + boundedCapacity].IsCompleted, "Remaining sends should not yet be completed");
}
Assert.True(b.Receive() == i, "Received value should match sent value in correct order");
Assert.True(tasks[i].Wait(WAIT_TIMEOUT) && tasks[i].Result, "Next sender task should have completed");
}
}
Assert.True(localPassed, string.Format("{0}: Correct ordering", localPassed ? "Success" : "Failure"));
}
// Test declining
{
bool localPassed = true;
for (int boundedCapacity = 1; boundedCapacity <= 3 && localPassed; boundedCapacity += 2)
{
var b = new BufferBlock<string>(new DataflowBlockOptions { BoundedCapacity = boundedCapacity });
int total = boundedCapacity + 2;
var tasks = new Task<bool>[total];
for (int i = 0; i < total; i++)
{
tasks[i] = b.SendAsync(i.ToString());
}
for (int i = 0; i < total; i++)
{
Assert.True((i < boundedCapacity) == tasks[i].IsCompleted, "All sends below the capacity should have completed");
//.........这里部分代码省略.........
示例13: NonGreedyJoin3WithBoundedCapacityTest
public void NonGreedyJoin3WithBoundedCapacityTest ()
{
var scheduler = new TestScheduler ();
var block = new JoinBlock<int, int, int> (
new GroupingDataflowBlockOptions
{ Greedy = false, BoundedCapacity = 1, TaskScheduler = scheduler });
var source1 =
new BufferBlock<int> (new DataflowBlockOptions { TaskScheduler = scheduler });
var source2 =
new BufferBlock<int> (new DataflowBlockOptions { TaskScheduler = scheduler });
var source3 =
new BufferBlock<int> (new DataflowBlockOptions { TaskScheduler = scheduler });
Assert.IsNotNull (source1.LinkTo (block.Target1));
Assert.IsNotNull (source2.LinkTo (block.Target2));
Assert.IsNotNull (source3.LinkTo (block.Target3));
Assert.IsTrue (source1.Post (11));
Assert.IsTrue (source2.Post (21));
Assert.IsTrue (source3.Post (31));
scheduler.ExecuteAll ();
Assert.IsTrue (source1.Post (12));
Assert.IsTrue (source2.Post (22));
Assert.IsTrue (source3.Post (32));
scheduler.ExecuteAll ();
int i;
Assert.IsTrue (source1.TryReceive (out i));
Assert.AreEqual (12, i);
Assert.IsTrue (source1.Post (13));
Tuple<int, int, int> tuple;
Assert.IsTrue (block.TryReceive (out tuple));
Assert.AreEqual (Tuple.Create (11, 21, 31), tuple);
scheduler.ExecuteAll ();
Assert.IsTrue (block.TryReceive (out tuple));
Assert.AreEqual (Tuple.Create (13, 22, 32), tuple);
}
示例14: TestReleaseOnReserveException
public async Task TestReleaseOnReserveException()
{
foreach (bool linkBadFirst in DataflowTestHelpers.BooleanValues)
{
var goodSource = new BufferBlock<int>();
goodSource.Post(1);
DelegatePropagator<int, int> badSource = null;
badSource = new DelegatePropagator<int, int>
{
LinkToDelegate = (target, options) => {
target.OfferMessage(new DataflowMessageHeader(1), 2, badSource, consumeToAccept: true);
return new DelegateDisposable();
},
ReserveMessageDelegate = delegate { throw new InvalidCastException(); }
};
var batch = new BatchBlock<int>(2, new GroupingDataflowBlockOptions { Greedy = false });
if (linkBadFirst) // Each linking will offer a message
{
badSource.LinkTo(batch);
goodSource.LinkTo(batch);
}
else
{
goodSource.LinkTo(batch);
badSource.LinkTo(batch);
}
await Assert.ThrowsAnyAsync<InvalidCastException>(() => batch.Completion);
int item;
Assert.True(goodSource.TryReceive(out item)); // The good message must not be Reserved
}
}
示例15: NonGreedyBatchWithMoreSourcesTest
public void NonGreedyBatchWithMoreSourcesTest ()
{
var scheduler = new TestScheduler ();
var block = new BatchBlock<int> (2,
new GroupingDataflowBlockOptions
{ Greedy = false, TaskScheduler = scheduler });
var source1 =
new BufferBlock<int> (new DataflowBlockOptions { TaskScheduler = scheduler });
var source2 =
new BufferBlock<int> (new DataflowBlockOptions { TaskScheduler = scheduler });
Assert.IsNotNull (source1.LinkTo (block));
Assert.IsNotNull (source2.LinkTo (block));
Assert.IsTrue (source1.Post (43));
scheduler.ExecuteAll ();
int i;
Assert.IsTrue (source1.TryReceive (out i));
Assert.AreEqual (43, i);
Assert.IsTrue (source1.Post (44));
Assert.IsTrue (source2.Post (45));
scheduler.ExecuteAll ();
int[] batch;
Assert.IsTrue (block.TryReceive (out batch));
CollectionAssert.AreEquivalent (new[] { 44, 45 }, batch);
}