本文整理汇总了C#中BufferBlock.TryReceiveAll方法的典型用法代码示例。如果您正苦于以下问题:C# BufferBlock.TryReceiveAll方法的具体用法?C# BufferBlock.TryReceiveAll怎么用?C# BufferBlock.TryReceiveAll使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类BufferBlock
的用法示例。
在下文中一共展示了BufferBlock.TryReceiveAll方法的12个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: TestReadOneLoadingTx
public void TestReadOneLoadingTx()
{
var coreStorageMock = new Mock<ICoreStorage>();
// create a fake transaction with 4 inputs
var prevTxCount = 4;
var txIndex = 1;
var chainedHeader = RandomData.RandomChainedHeader();
// create previous transactions for 4 inputs
var prevTxes = new Transaction[prevTxCount];
var inputs = new TxInput[prevTxCount];
for (var i = 0; i < prevTxCount; i++)
{
var prevTx = RandomData.RandomTransaction();
var prevBlockTx = (BlockTx)BlockTx.Create(i, prevTx);
prevTxes[i] = prevTx;
inputs[i] = new TxInput(prevTx.Hash, 0, ImmutableArray.Create<byte>(), 0);
// mock retrieval of the previous transaction
coreStorageMock.Setup(coreStorage => coreStorage.TryGetTransaction(UInt256.Zero, i, out prevBlockTx)).Returns(true);
}
// create a loading tx with the 4 inputs referencing block hash 0
var tx = RandomData.RandomTransaction(new RandomDataOptions { TxOutputCount = 1 })
.CreateWith(Inputs: inputs.ToImmutableArray()).Transaction;
var prevOutputTxKeys = ImmutableArray.CreateRange(
Enumerable.Range(0, prevTxCount).Select(x => new TxLookupKey(UInt256.Zero, x)));
var loadingTx = new LoadingTx(txIndex, tx, chainedHeader, prevOutputTxKeys);
// begin queuing transactions to load
var loadingTxes = new BufferBlock<LoadingTx>();
loadingTxes.Post(loadingTx);
loadingTxes.Complete();
// begin transaction loading
var txLoader = TxLoader.LoadTxes(coreStorageMock.Object, loadingTxes);
// verify the loaded transaction
var loadedTxesBuffer = new BufferBlock<LoadedTx>();
txLoader.LinkTo(loadedTxesBuffer, new DataflowLinkOptions { PropagateCompletion = true });
txLoader.Completion.Wait();
IList<LoadedTx> actualLoadedTxes;
Assert.IsTrue(loadedTxesBuffer.TryReceiveAll(out actualLoadedTxes));
var actualLoadedTx = actualLoadedTxes.Single();
Assert.AreEqual(loadingTx.TxIndex, actualLoadedTx.TxIndex);
Assert.AreEqual(loadingTx.Transaction, actualLoadedTx.Transaction);
CollectionAssert.AreEqual(prevTxes.Select(x => x.Hash).ToArray(), actualLoadedTx.InputTxes.Select(x => x.Hash).ToArray());
}
示例2: TestPrecanceled
public async Task TestPrecanceled()
{
var bb = new BufferBlock<int>(
new DataflowBlockOptions { CancellationToken = new CancellationToken(canceled: true) });
int ignoredValue;
IList<int> ignoredValues;
IDisposable link = bb.LinkTo(DataflowBlock.NullTarget<int>());
Assert.NotNull(link);
link.Dispose();
Assert.False(bb.Post(42));
var t = bb.SendAsync(42);
Assert.True(t.IsCompleted);
Assert.False(t.Result);
Assert.Equal(expected: 0, actual: bb.Count);
Assert.False(bb.TryReceiveAll(out ignoredValues));
Assert.False(bb.TryReceive(out ignoredValue));
Assert.NotNull(bb.Completion);
await Assert.ThrowsAnyAsync<OperationCanceledException>(() => bb.Completion);
bb.Complete(); // just make sure it doesn't throw
}
示例3: TestOutputAvailableAsyncAfterTryReceiveAll
[OuterLoop] // has a timeout
public async Task TestOutputAvailableAsyncAfterTryReceiveAll()
{
Func<Task<bool>> generator = () => {
var buffer = new BufferBlock<object>();
buffer.Post(null);
IList<object> items;
buffer.TryReceiveAll(out items);
var outputAvailableAsync = buffer.OutputAvailableAsync();
buffer.Post(null);
return outputAvailableAsync;
};
var multipleConcurrentTestsTask = Task.WhenAll(Enumerable.Repeat(0, 1000).Select(_ => generator()));
var timeoutTask = Task.Delay(2000);
var completedTask = await Task.WhenAny(multipleConcurrentTestsTask, timeoutTask).ConfigureAwait(false);
Assert.True(completedTask != timeoutTask);
}
示例4: TestBoundedReceives
public async Task TestBoundedReceives()
{
for (int test = 0; test < 4; test++)
{
var bb = new BufferBlock<int>(new DataflowBlockOptions { BoundedCapacity = 1 });
Assert.True(bb.Post(0));
const int sends = 5;
for (int i = 1; i <= sends; i++)
{
Task<bool> send = bb.SendAsync(i);
Assert.True(await bb.OutputAvailableAsync()); // wait for previously posted/sent item
int item;
switch (test)
{
case 0:
IList<int> items;
Assert.True(bb.TryReceiveAll(out items));
Assert.Equal(expected: 1, actual: items.Count);
Assert.Equal(expected: i - 1, actual: items[0]);
break;
case 1:
Assert.True(bb.TryReceive(f => true, out item));
Assert.Equal(expected: i - 1, actual: item);
break;
case 2:
Assert.False(bb.TryReceive(f => f == i, out item));
Assert.True(bb.TryReceive(f => f == i - 1, out item));
Assert.Equal(expected: i - 1, actual: item);
break;
case 3:
Assert.Equal(expected: i - 1, actual: await bb.ReceiveAsync());
break;
}
}
// Receive remaining item
Assert.Equal(expected: sends, actual: await bb.ReceiveAsync());
bb.Complete();
await bb.Completion;
}
}
示例5: 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;
}
}
}
示例6: SeedAsync
public async static Task<Animat> SeedAsync(ScenarioSpecies species, GeoRect geoRect, Bathymetry bathymetry)
{
var yxzFileName = Path.Combine(Path.GetTempPath(), Path.GetFileNameWithoutExtension(Path.GetRandomFileName()) + ".txt");
bathymetry.ToYXZ(yxzFileName, -1);
var mbs = new C3mbs();
mbsRESULT mbsResult;
if (mbsRESULT.OK != (mbsResult = mbs.SetOutputDirectory(Path.GetTempPath())))
throw new AnimatInterfaceMMBSException("SetOutputDirectory Error:" + mbs.ResultToTc(mbsResult));
var config = mbs.GetConfiguration();
config.enabled = false; // binary output enabled/disabled
config.durationLess = true; // make sure we're in durationless mode.
mbs.SetConfiguration(config);
mbsResult = mbs.LoadBathymetryFromTextFile(yxzFileName);
if (mbsRESULT.OK != mbsResult) throw new AnimatInterfaceMMBSException("Bathymetry failed to load: " + mbs.ResultToTc(mbsResult));
mbsResult = mbs.AddSpecies(species.SpeciesDefinitionFilePath);
if (mbsRESULT.OK != mbsResult) throw new AnimatInterfaceMMBSException(string.Format("C3mbs::AddSpecies FATAL error {0} for species {1}", mbs.ResultToTc(mbsResult), species.SpeciesDefinitionFilePath));
var bounds = new GeoArray(geoRect.NorthWest, geoRect.NorthEast, geoRect.SouthEast, geoRect.SouthWest, geoRect.NorthWest);
var result = new Animat { ScenarioSpecies = species };
var area = bounds.Area;
//Debug.WriteLine("Area: {0}",area);
var transformManyBlock = new TransformManyBlock<int, Geo<float>>(count =>
{
var geos = new List<Geo<float>>();
for (var i = 0; i < count; i++)
{
var location = bounds.RandomLocationWithinPerimeter();
var depth = bathymetry.Samples.GetNearestPointAsync(location).Result.Data;
mbsRESULT retval;
lock (mbs) retval = mbs.AddIndividualAnimat(0, new mbsPosition { latitude = location.Latitude, longitude = location.Longitude, depth = 0 });
if (mbsRESULT.OK == retval) geos.Add(new Geo<float>(location.Latitude, location.Longitude, (float)(depth * Random.NextDouble())));
}
return geos;
}, new ExecutionDataflowBlockOptions
{
TaskScheduler = TaskScheduler.Default,
BoundedCapacity = -1,
MaxDegreeOfParallelism = -1,
});
var bufferBlock = new BufferBlock<Geo<float>>();
transformManyBlock.LinkTo(bufferBlock);
var population = (int)Math.Round(area * species.PopulationDensity);
result.TotalAnimats = population;
const int blockSize = 100;
while (population > 0)
{
transformManyBlock.Post(population > blockSize ? blockSize : population);
population -= blockSize;
}
transformManyBlock.Complete();
await transformManyBlock.Completion;
//mbsResult = mbs.InitializeRun();
//if (mbsRESULT.OK == mbsResult) while (mbsRUNSTATE.INITIALIZING == mbs.GetRunState()) Thread.Sleep(1);
//else throw new AnimatInterfaceMMBSException("C3mbs::Initialize FATAL error " + mbs.ResultToTc(mbsResult));
mbsResult = mbs.FinishRun();
if (mbsRESULT.OK != mbsResult) throw new AnimatInterfaceMMBSException("C3mbs::FinishRun FATAL error " + mbs.ResultToTc(mbsResult));
IList<Geo<float>> animatGeos;
if (bufferBlock.TryReceiveAll(out animatGeos))
result.Locations.AddRange(animatGeos);
return result;
}
示例7: SeedAsyncWithout3MB
public async static Task<Animat> SeedAsyncWithout3MB(ScenarioSpecies species, GeoRect geoRect, Bathymetry bathymetry)
{
var bounds = new GeoArray(geoRect.NorthWest, geoRect.NorthEast, geoRect.SouthEast, geoRect.SouthWest, geoRect.NorthWest);
var result = new Animat { ScenarioSpecies = species };
var area = bounds.Area;
//Debug.WriteLine("Area: {0}",area);
var transformManyBlock = new TransformManyBlock<int, Geo<float>>(count =>
{
var geos = new List<Geo<float>>();
for (var i = 0; i < count; i++)
{
var location = bounds.RandomLocationWithinPerimeter();
var depth = bathymetry.Samples.GetNearestPointAsync(location).Result.Data;
if (depth < -50) geos.Add(new Geo<float>(location.Latitude, location.Longitude, (float)(depth * Random.NextDouble())));
}
return geos;
}, new ExecutionDataflowBlockOptions
{
TaskScheduler = TaskScheduler.Default,
BoundedCapacity = -1,
MaxDegreeOfParallelism = -1,
});
var bufferBlock = new BufferBlock<Geo<float>>();
transformManyBlock.LinkTo(bufferBlock);
var population = (int)Math.Round(area * species.PopulationDensity);
result.TotalAnimats = population;
const int blockSize = 100;
while (population > 0)
{
transformManyBlock.Post(population > blockSize ? blockSize : population);
population -= blockSize;
}
transformManyBlock.Complete();
await transformManyBlock.Completion;
IList<Geo<float>> animatGeos;
if (bufferBlock.TryReceiveAll(out animatGeos))
result.Locations.AddRange(animatGeos);
return result;
}
示例8: TestOutputAvailableAsyncAfterTryReceiveAll
public async Task TestOutputAvailableAsyncAfterTryReceiveAll()
{
Func<Task<bool>> generator = () => {
var buffer = new BufferBlock<object>();
buffer.Post(null);
IList<object> items;
buffer.TryReceiveAll(out items);
var outputAvailableAsync = buffer.OutputAvailableAsync();
buffer.Post(null);
return outputAvailableAsync;
};
bool[] results = await Task.WhenAll(Enumerable.Repeat(0, 10).Select(_ => generator()));
Assert.All(results, Assert.True);
}
示例9: TestBufferBlockBounding
//.........这里部分代码省略.........
{
bool localPassed = true;
const int ITERS = 2;
for (int boundedCapacity = 1; boundedCapacity <= 3 && localPassed; boundedCapacity += 2)
{
var b = new BufferBlock<int>(new DataflowBlockOptions { BoundedCapacity = boundedCapacity });
var p = Task.Factory.StartNew(() =>
{
Assert.True(b.Count == 0, "Nothing should be in the buffer yet");
for (int i = 0; i < ITERS; i++)
{
if (!b.SendAsync(i).Wait(WAIT_TIMEOUT))
{
localPassed = false;
Assert.True(localPassed, "Send should have completed within timeout");
}
}
});
var c = Task.Factory.StartNew(() =>
{
for (int i = 0; i < ITERS; i++)
{
var t = b.ReceiveAsync();
if (!t.Wait(WAIT_TIMEOUT))
{
localPassed = false;
Assert.True(localPassed, "Receive should have completed within timeout");
}
if (t.Status != TaskStatus.RanToCompletion || t.Result != i)
{
localPassed = false;
Assert.True(localPassed, "Receive should have completed with correct value");
}
}
Assert.True(b.Count == 0, "The buffer should be empty after all items received");
});
if (!Task.WaitAll(new[] { p, c }, WAIT_TIMEOUT))
{
localPassed = false;
Assert.True(localPassed, "Both producer and consumer should have completed in allotted time");
}
}
}
// Test multi-item removal
{
bool localPassed = true;
for (int boundedCapacity = 1; boundedCapacity <= 3 && localPassed; boundedCapacity += 2)
{
var b = new BufferBlock<int>(new DataflowBlockOptions { BoundedCapacity = boundedCapacity });
for (int iter = 0; iter < 2; iter++)
{
for (int i = 0; i < boundedCapacity; i++)
{
var send = b.SendAsync(i);
localPassed &= send.Wait(0) && send.Result;
}
IList<int> output;
Assert.True(b.TryReceiveAll(out output), "Data should have been available");
Assert.True(output.Count == boundedCapacity, "Should have removed all posted items");
}
}
}
// Test releasing of postponed messages
{
const int excess = 10;
bool localPassed = true;
for (int boundedCapacity = 1; boundedCapacity <= 3 && localPassed; boundedCapacity += 2)
{
for (int iter = 0; iter < 2; iter++)
{
var b = new BufferBlock<int>(new DataflowBlockOptions { BoundedCapacity = boundedCapacity });
var sendAsync = new Task<bool>[boundedCapacity + excess];
for (int i = 0; i < boundedCapacity + excess; i++) sendAsync[i] = b.SendAsync(i);
b.Complete();
for (int i = 0; i < boundedCapacity; i++)
{
Assert.True(sendAsync[i].Result, string.Format("bc={0} iter={1} send failed but should have succeeded", boundedCapacity, iter));
}
for (int i = 0; i < excess; i++)
{
Assert.True(!sendAsync[boundedCapacity + i].Result, string.Format("bc={0} iter={1} send succeeded but should have failed", boundedCapacity, iter));
}
}
}
}
}
示例10: RunBufferBlockConformanceTests
public void RunBufferBlockConformanceTests()
{
bool localPassed;
// Do everything twice - once through OfferMessage and Once through Post
for (FeedMethod feedMethod = FeedMethod._First; feedMethod < FeedMethod._Count; feedMethod++)
{
Func<DataflowBlockOptions, TargetProperties<int>> bufferBlockFactory =
options =>
{
BufferBlock<int> bufferBlock = new BufferBlock<int>(options);
ActionBlock<int> actionBlock = new ActionBlock<int>(i => TrackCaptures(i), (ExecutionDataflowBlockOptions)options);
bufferBlock.LinkTo(actionBlock);
return new TargetProperties<int> { Target = bufferBlock, Capturer = actionBlock, ErrorVerifyable = false };
};
CancellationTokenSource cancellationSource = new CancellationTokenSource();
var defaultOptions = new ExecutionDataflowBlockOptions();
var dopOptions = new ExecutionDataflowBlockOptions { MaxDegreeOfParallelism = Environment.ProcessorCount };
var mptOptions = new ExecutionDataflowBlockOptions { MaxDegreeOfParallelism = Environment.ProcessorCount, MaxMessagesPerTask = 10 };
var cancellationOptions = new ExecutionDataflowBlockOptions { MaxDegreeOfParallelism = Environment.ProcessorCount, MaxMessagesPerTask = 100, CancellationToken = cancellationSource.Token };
Assert.True(FeedTarget(bufferBlockFactory, defaultOptions, 1, Intervention.None, null, feedMethod, true));
Assert.True(FeedTarget(bufferBlockFactory, defaultOptions, 10, Intervention.None, null, feedMethod, true));
Assert.True(FeedTarget(bufferBlockFactory, dopOptions, 1000, Intervention.None, null, feedMethod, true));
Assert.True(FeedTarget(bufferBlockFactory, mptOptions, 10000, Intervention.None, null, feedMethod, true));
Assert.True(FeedTarget(bufferBlockFactory, mptOptions, 10000, Intervention.Complete, null, feedMethod, true));
Assert.True(FeedTarget(bufferBlockFactory, cancellationOptions, 10000, Intervention.Cancel, cancellationSource, feedMethod, true));
}
// Test chained Post/Receive
{
localPassed = true;
const int ITERS = 2;
var network = Chain<BufferBlock<int>, int>(4, () => new BufferBlock<int>());
for (int i = 0; i < ITERS; i++)
{
network.Post(i);
localPassed &= (((IReceivableSourceBlock<int>)network).Receive() == i);
}
Assert.True(localPassed, string.Format("{0}: Chained Post/Receive", localPassed ? "Success" : "Failure"));
}
// Test chained SendAsync/Receive
{
localPassed = true;
const int ITERS = 2;
var network = Chain<BufferBlock<int>, int>(4, () => new BufferBlock<int>());
for (int i = 0; i < ITERS; i++)
{
network.SendAsync(i);
localPassed &= (((IReceivableSourceBlock<int>)network).Receive() == i);
}
Assert.True(localPassed, string.Format("{0}: Chained SendAsync/Receive", localPassed ? "Success" : "Failure"));
}
// Test chained Post all then Receive
{
localPassed = true;
const int ITERS = 2;
var network = Chain<BufferBlock<int>, int>(4, () => new BufferBlock<int>());
for (int i = 0; i < ITERS; i++) localPassed &= network.Post(i) == true;
for (int i = 0; i < ITERS; i++) localPassed &= ((IReceivableSourceBlock<int>)network).Receive() == i;
Assert.True(localPassed, string.Format("{0}: Chained Post all then Receive", localPassed ? "Success" : "Failure"));
}
// Test chained SendAsync all then Receive
{
localPassed = true;
const int ITERS = 2;
var network = Chain<BufferBlock<int>, int>(4, () => new BufferBlock<int>());
var tasks = new Task[ITERS];
for (int i = 1; i <= ITERS; i++) tasks[i - 1] = network.SendAsync(i);
Task.WaitAll(tasks);
int total = 0;
for (int i = 1; i <= ITERS; i++) total += ((IReceivableSourceBlock<int>)network).Receive();
localPassed &= (total == ((ITERS * (ITERS + 1)) / 2));
Assert.True(localPassed, string.Format("{0}: Chained SendAsync all then Receive", localPassed ? "Success" : "Failure"));
}
// Test using a precanceled token
{
localPassed = true;
try
{
var cts = new CancellationTokenSource();
cts.Cancel();
var dbo = new DataflowBlockOptions { CancellationToken = cts.Token };
var bb = new BufferBlock<int>(dbo);
int ignoredValue;
IList<int> ignoredValues;
localPassed &= bb.LinkTo(new ActionBlock<int>(delegate { })) != null;
localPassed &= bb.SendAsync(42).Result == false;
localPassed &= bb.TryReceiveAll(out ignoredValues) == false;
localPassed &= bb.Post(42) == false;
localPassed &= bb.Count == 0;
localPassed &= bb.TryReceive(out ignoredValue) == false;
localPassed &= bb.Completion != null;
bb.Complete();
//.........这里部分代码省略.........
示例11: TestBufferBlockCount
public void TestBufferBlockCount()
{
BufferBlock<int> bufferBlock = new BufferBlock<int>();
Assert.False(bufferBlock.Count != 0, "BufferBlock.Count failed! an initialized block has a non zero count");
for (int i = 0; i < 10; i++)
{
((ITargetBlock<int>)bufferBlock).OfferMessage(new DataflowMessageHeader(1 + i), i, null, false); // Message ID doesn't matter because consumeTosAccept:false
}
Assert.False(bufferBlock.Count != 10, string.Format("BufferBlock.Count failed! expected {0}, actual {1}", 10, bufferBlock.Count));
IList<int> items;
bool result = bufferBlock.TryReceiveAll(out items);
Assert.False(bufferBlock.Count != 0, string.Format("BufferBlock.Count failed! expected {0}, actual {1}", 0, bufferBlock.Count));
}
示例12: GetOutputAvailableAsyncTaskAfterTryReceiveAllOnNonEmptyBufferBlock
private Task GetOutputAvailableAsyncTaskAfterTryReceiveAllOnNonEmptyBufferBlock()
{
var buffer = new BufferBlock<object>();
buffer.Post(null);
IList<object> items;
buffer.TryReceiveAll(out items);
var outputAvailableAsync = buffer.OutputAvailableAsync();
buffer.Post(null);
return outputAvailableAsync;
}