本文整理汇总了C#中BufferBlock.LinkTo方法的典型用法代码示例。如果您正苦于以下问题:C# BufferBlock.LinkTo方法的具体用法?C# BufferBlock.LinkTo怎么用?C# BufferBlock.LinkTo使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类BufferBlock
的用法示例。
在下文中一共展示了BufferBlock.LinkTo方法的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: ExecutionPipeline
public ExecutionPipeline(Kernel kernel)
{
_kernel = kernel;
_commandQueue = new BufferBlock<CommandRequest[]>();
_queryQueue = new BatchBlock<QueryRequest>(MaxConcurrentQueries);
var transactionHandler = new ActionBlock<object>(t =>
{
if (t is QueryRequest[])
{
var queries = t as QueryRequest[];
Task[] tasks = queries.Select(q => Task.Factory.StartNew(_ => ExecuteQuery(q), null)).ToArray();
Task.WaitAll(tasks);
}
else if (t is CommandRequest[])
{
var commands = t as CommandRequest[];
foreach (var commandContext in commands)
{
var result = _kernel.Execute(commandContext.Command);
commandContext.Response.Post(result);
}
}
});
_commandQueue.LinkTo(transactionHandler);
_queryQueue.LinkTo(transactionHandler);
_timer = new Timer(_ => _queryQueue.TriggerBatch());
_timer.Change(Interval, Interval);
}
示例3: MultipleBindingTest
public void MultipleBindingTest ()
{
BufferBlock<int> buffer = new BufferBlock<int> ();
var evt = new CountdownEvent (10);
int count = 0;
ActionBlock<int> block = new ActionBlock<int> ((i) => { Interlocked.Decrement (ref count); evt.Signal (); });
IDisposable bridge = buffer.LinkTo (block);
for (int i = 0; i < 10; i++)
Assert.IsTrue (buffer.Post (i));
evt.Wait ();
Assert.AreEqual (-10, count);
count = 0;
evt.Reset ();
bridge.Dispose ();
ActionBlock<int> block2 = new ActionBlock<int> ((i) => { Interlocked.Increment (ref count); evt.Signal (); });
buffer.LinkTo (block2);
for (int i = 0; i < 10; i++)
Assert.IsTrue (buffer.Post (i));
evt.Wait ();
Assert.AreEqual (10, count);
}
示例4: Run
public void Run()
{
var cts = new CancellationTokenSource();
Console.WriteLine("Generating first {0} powers of 2.", MaxItems);
var bufferBlock = new BufferBlock<int>(new DataflowBlockOptions { CancellationToken = cts.Token });
Enumerable.Range(1, MaxItems)
.ToList()
.ForEach(i => bufferBlock.Post(i));
Console.WriteLine("Scheduling cancellation after 5 seconds.");
cts.CancelAfter(TimeSpan.FromSeconds(5));
Console.WriteLine("Creating and linking the remaing blocks to the network.");
var transformBlock = new TransformBlock<int, double>(i =>
{
Thread.Sleep(500);
return Math.Pow(2, i);
}, new ExecutionDataflowBlockOptions { BoundedCapacity = 1, CancellationToken = cts.Token });
var actionBlock = new ActionBlock<double>(async i =>
{
await Task.Delay(1000);
Console.WriteLine(i);
}, new ExecutionDataflowBlockOptions { BoundedCapacity = 10, CancellationToken = cts.Token });
bufferBlock.LinkTo(transformBlock, new DataflowLinkOptions { PropagateCompletion = true });
transformBlock.LinkTo(actionBlock, new DataflowLinkOptions { PropagateCompletion = true });
var t1 = bufferBlock.Completion.ContinueWith(t => Console.WriteLine("Buffer block status: {0}", t.Status));
var t2 = actionBlock.Completion.ContinueWith(t => Console.WriteLine("Action block status: {0}", t.Status));
Console.WriteLine("Waiting for the network to finish.");
Task.WaitAll(t1, t2);
}
示例5: Generate
public static void Generate(string root)
{
Directory.CreateDirectory("docs");
var _executingDirectory = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
File.Copy(Path.Combine(_executingDirectory, "Resources", "Nocco.css"), Path.Combine("docs", "nocco.css"), true);
File.Copy(Path.Combine(_executingDirectory, "Resources", "prettify.js"), Path.Combine("docs", "prettify.js"), true);
var getFiles = DirectoryTraveler.Create();
var readFiles = FileReader.Create();
var redFileBuffer = new BufferBlock<FileContents>();
var parseFiles = FileParser.Create();
var renderCode = CodeRenderer.Create();
var renderDocs = DocRenderer.Create();
var generateHtml = HtmlGenerator.Create();
var persistanceBuffer = new BufferBlock<RenderedFile>();
var persistFile = FilePersister.Create();
var propCompl = new DataflowLinkOptions { PropagateCompletion = true };
getFiles.LinkTo(readFiles, propCompl);
readFiles.LinkTo(redFileBuffer, propCompl);
redFileBuffer.LinkTo(parseFiles, propCompl);
parseFiles.LinkTo(renderCode, propCompl);
renderCode.LinkTo(renderDocs, propCompl);
renderDocs.LinkTo(generateHtml, propCompl);
generateHtml.LinkTo(persistanceBuffer, propCompl);
persistanceBuffer.LinkTo(persistFile, propCompl);
getFiles.Post(root);
getFiles.Complete();
persistanceBuffer.Completion.Wait();
}
示例6: Run
public void Run()
{
Console.WriteLine("Generating first {0} powers of 2.", MaxItems);
var bufferBlock = new BufferBlock<int>();
var transformBlock = new TransformBlock<int, double>(i =>
{
Thread.Sleep(500);
return Math.Pow(2, i);
}, new ExecutionDataflowBlockOptions { BoundedCapacity = 10 });
var actionBlock = new ActionBlock<double>(async i =>
{
await Task.Delay(1000);
Console.WriteLine(i);
_waitHandle.Signal();
}, new ExecutionDataflowBlockOptions { BoundedCapacity = 10 });
bufferBlock.LinkTo(transformBlock);
transformBlock.LinkTo(actionBlock);
Enumerable.Range(1, MaxItems)
.ToList()
.ForEach(i => bufferBlock.Post(i));
_waitHandle.Wait();
}
示例7: ProduceLogs
public void ProduceLogs(int count, int buffSize)
{
var bufferOptions = new DataflowBlockOptions() { BoundedCapacity = buffSize };
var writerOptions = new ExecutionDataflowBlockOptions() { BoundedCapacity = 10, MaxDegreeOfParallelism = 1, MaxMessagesPerTask = 10, SingleProducerConstrained = true };
LogGenerator g = new LogGenerator();
var file = new StreamWriter("basic.async.buff.log", false);
BufferBlock<string> buffer = new BufferBlock<string>(bufferOptions);
ActionBlock<string> writer = new ActionBlock<string>(s => file.WriteLine(s), writerOptions);
buffer.LinkTo(writer, new DataflowLinkOptions() { PropagateCompletion = true });
for (int i = 0; i < count; i++)
{
g.Next();
var line = string.Format(g.FormatStr, g.Param1, g.Param2, g.Param3, g.Param4, g.Param5, g.Param6);
writer.SendAsync(line).Wait();
}
buffer.Complete();
Completed = writer.Completion.ContinueWith(t => file.Close());
}
示例8: Run
public void Run()
{
Console.WriteLine("Generating first {0} powers of 2.", MaxItems);
var bufferBlock = new BufferBlock<int>();
Enumerable.Range(1, MaxItems)
.ToList()
.ForEach(i => bufferBlock.Post(i));
Console.WriteLine("Signaling completion to the source block.");
bufferBlock.Complete();
Console.WriteLine("Done.");
Console.WriteLine("Creating and linking the remaing blocks to the network.");
var transformBlock = new TransformBlock<int, double>(i =>
{
Thread.Sleep(200);
return Math.Pow(2, i);
}, new ExecutionDataflowBlockOptions { BoundedCapacity = 1 });
var actionBlock = new ActionBlock<double>(async i =>
{
await Task.Delay(500);
Console.WriteLine(i);
}, new ExecutionDataflowBlockOptions { BoundedCapacity = 10 });
bufferBlock.LinkTo(transformBlock, new DataflowLinkOptions { PropagateCompletion = true });
transformBlock.LinkTo(actionBlock, new DataflowLinkOptions { PropagateCompletion = true });
Console.WriteLine("Waiting for the completion to be propagated through the network...");
actionBlock.Completion.ContinueWith(t =>
{
Console.WriteLine("Finished processing.");
Console.WriteLine(string.Format("Completion status: {0}.", t.Status));
}).Wait();
}
示例9: Start
public void Start()
{
var sink = new ActionBlock<PageResultMessage>((Action<PageResultMessage>)Sink);
var source = new BufferBlock<GetPageMessage>();
var linkOptions = new DataflowLinkOptions {PropagateCompletion = false};
for (int i = 0; i < 10; i++)
{
var options = new ExecutionDataflowBlockOptions
{
BoundedCapacity = 1
};
var worker = new TransformBlock<GetPageMessage, PageResultMessage>(
(Func<GetPageMessage, PageResultMessage>)Worker, options);
source.LinkTo(worker, linkOptions);
worker.LinkTo(sink, linkOptions);
}
foreach (var url in UrlList.Urls)
{
source.Post(new GetPageMessage{ Url = url });
}
source.Complete();
sink.Completion.Wait();
}
示例10: ReplayRollbackUtxo
public static ISourceBlock<ValidatableTx> ReplayRollbackUtxo(ICoreStorage coreStorage, IChainState chainState, ChainedHeader replayBlock, CancellationToken cancelToken = default(CancellationToken))
{
// replaying rollback of an on-chain block, use the chainstate tx index for replay, same as replaying forward
if (chainState.Chain.BlocksByHash.ContainsKey(replayBlock.Hash))
{
return ReplayFromTxIndex(coreStorage, chainState, replayBlock, replayForward: false, cancelToken: cancelToken);
}
// replaying rollback of an off-chain (re-org) block, use the unminted information for replay
else
{
IImmutableList<UnmintedTx> unmintedTxesList;
if (!chainState.TryGetBlockUnmintedTxes(replayBlock.Hash, out unmintedTxesList))
{
//TODO if a wallet/monitor were to see a chainstate block that wasn't flushed to disk yet,
//TODO and if bitsharp crashed, and if the block was orphaned: then the orphaned block would
//TODO not be present in the chainstate, and it would not get rolled back to generate unminted information.
//TODO DeferredChainStateCursor should be used in order to re-org the chainstate in memory and calculate the unminted information
throw new MissingDataException(replayBlock.Hash);
}
var unmintedTxes = ImmutableDictionary.CreateRange(
unmintedTxesList.Select(x => new KeyValuePair<UInt256, UnmintedTx>(x.TxHash, x)));
var lookupLoadingTx = new TransformBlock<DecodedBlockTx, ValidatableTx>(
blockTx =>
{
var tx = blockTx.Transaction;
var txIndex = blockTx.Index;
var prevTxOutputs = ImmutableArray.CreateBuilder<PrevTxOutput>(!blockTx.IsCoinbase ? tx.Inputs.Length : 0);
if (!blockTx.IsCoinbase)
{
UnmintedTx unmintedTx;
if (!unmintedTxes.TryGetValue(tx.Hash, out unmintedTx))
throw new MissingDataException(replayBlock.Hash);
prevTxOutputs.AddRange(unmintedTx.PrevTxOutputs);
}
return new ValidatableTx(blockTx, replayBlock, prevTxOutputs.MoveToImmutable());
});
IEnumerator<BlockTx> blockTxes;
if (!coreStorage.TryReadBlockTransactions(replayBlock.Hash, out blockTxes))
{
throw new MissingDataException(replayBlock.Hash);
}
var blockTxesBuffer = new BufferBlock<DecodedBlockTx>();
blockTxesBuffer.LinkTo(lookupLoadingTx, new DataflowLinkOptions { PropagateCompletion = true });
blockTxesBuffer.SendAndCompleteAsync(blockTxes.UsingAsEnumerable().Select(x => x.Decode()).Reverse(), cancelToken).Forget();
return lookupLoadingTx;
}
}
示例11: PropagateCompletionSimpleTest
public void PropagateCompletionSimpleTest ()
{
var source = new BufferBlock<int> ();
var target = new BufferBlock<int> ();
Assert.IsNotNull (source.LinkTo (target,
new DataflowLinkOptions { PropagateCompletion = true }));
Assert.IsFalse (target.Completion.Wait (100));
source.Complete ();
Assert.IsTrue (target.Completion.Wait (100));
}
示例12: BasicUsageTest
public void BasicUsageTest ()
{
int data = -1;
var evt = new ManualResetEventSlim (false);
BufferBlock<int> buffer = new BufferBlock<int> ();
ActionBlock<int> action = new ActionBlock<int> ((i) => { data = i; evt.Set (); });
buffer.LinkTo (action);
Assert.IsTrue (buffer.Post (42));
evt.Wait ();
Assert.AreEqual (42, data);
}
示例13: Example2
public static void Example2()
{
// Scenario: one buffer and 3 actions connected to it - each number will be processed only by one action
var conf = new ExecutionDataflowBlockOptions();
// todo: play with those
conf.BoundedCapacity = 1;
conf.MaxDegreeOfParallelism = 4;
var buffer = new BufferBlock<int>();
var action1 = new ActionBlock<int>(a => {
Thread.Sleep(50);
Console.WriteLine("Action 1 value: {0}", a);
}, conf);
var action2 = new ActionBlock<int>(a =>
{
Thread.Sleep(50);
Console.WriteLine("Action 2 value: {0}", a);
}, conf);
var action3 = new ActionBlock<int>(a =>
{
Thread.Sleep(50);
Console.WriteLine("Action 3 value: {0}", a);
}, conf);
buffer.LinkTo(action1);
buffer.LinkTo(action2);
buffer.LinkTo(action3);
var t = new Task(() => {
for (int i = 0; i < 12; i++)
{
buffer.Post(i);
}
});
t.Start();
}
示例14: LateBindingTest
public void LateBindingTest ()
{
BufferBlock<int> buffer = new BufferBlock<int> ();
var evt = new CountdownEvent (10);
for (int i = 0; i < 10; i++)
Assert.IsTrue (buffer.Post (i));
ActionBlock<int> block = new ActionBlock<int> ((i) => evt.Signal ());
buffer.LinkTo (block);
evt.Wait ();
}
示例15: Init
/// <summary>
/// 初期化処理。
/// </summary>
/// <param name="settingObject"></param>
/// <param name="token"></param>
public void Init(dynamic settingObject, CancellationToken token)
{
logger.Trace("Init Start");
var opt = new DataflowBlockOptions
{
CancellationToken = token,
};
var buffer = new BufferBlock<PastaLog>(opt);
var bloadcast = new BroadcastBlock<PastaLog>(CloneLog, opt);
buffer.LinkTo(bloadcast);
Target = buffer;
Source = bloadcast;
logger.Trace("Init End");
}