本文整理汇总了C#中BufferBlock类的典型用法代码示例。如果您正苦于以下问题:C# BufferBlock类的具体用法?C# BufferBlock怎么用?C# BufferBlock使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
BufferBlock类属于命名空间,在下文中一共展示了BufferBlock类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的C#代码示例。
示例1: 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();
}
开发者ID:valdisz,项目名称:nocco,代码行数:34,代码来源:Flow.cs
示例2: Process
public async Task Process(GamePointer gp, List<PlayerState> players, BufferBlock<UpdatePacket> sendChannel)
{
players.Add(_player);
var squares = gp.Game.GetSquares().Select(x => new SquareDTO(x)).ToArray();
//FIXME: right now the order is important here, lest we lack player color information when rendering flags
var json2 = JSON.Serialize<PlayerState[]>(players.ToArray());
var packet2 = new UpdatePacket()
{
Type = "player",
Data = json2
};
var j2 = JSON.Serialize<UpdatePacket>(packet2);
await _uc.SendAsync(j2);
var json = JSON.Serialize<SquareDTO[]>(squares);
var packet = new UpdatePacket()
{
Type = "square",
Data = json
};
var j = JSON.Serialize<UpdatePacket>(packet);
await _uc.SendAsync(j);
}
开发者ID:slofurno,项目名称:minesweepers,代码行数:31,代码来源:Tasks.cs
示例3: SQLMessageQueue
public SQLMessageQueue(IDbConnectionProvider connectionProvider, ISQLDialect dialect, QueueName queueName,
IQueueListener listener, QueueOptions options = default(QueueOptions))
{
if (connectionProvider == null) throw new ArgumentNullException("connectionProvider");
if (dialect == null) throw new ArgumentNullException("dialect");
if (queueName == null) throw new ArgumentNullException("queueName");
if (listener == null) throw new ArgumentNullException("listener");
_connectionProvider = connectionProvider;
_dialect = dialect;
_queueName = queueName;
_listener = listener;
_autoAcknowledge = options.AutoAcknowledge;
_maxAttempts = options.MaxAttempts <= 0 ? 10 : options.MaxAttempts;
_retryDelay = options.RetryDelay < TimeSpan.Zero ? TimeSpan.Zero : options.RetryDelay;
var concurrencyLimit = options.ConcurrencyLimit <= 0
? QueueOptions.DefaultConcurrencyLimit
: options.ConcurrencyLimit;
_concurrentMessageProcessingSlot = new SemaphoreSlim(concurrencyLimit);
_cancellationTokenSource = new CancellationTokenSource();
_queuedMessages = new BufferBlock<SQLQueuedMessage>(new DataflowBlockOptions
{
CancellationToken = _cancellationTokenSource.Token
});
}
开发者ID:tdbrian,项目名称:Platibus,代码行数:28,代码来源:SQLMessageQueue.cs
示例4: FilesystemMessageQueue
public FilesystemMessageQueue(DirectoryInfo directory, IQueueListener listener,
QueueOptions options = default(QueueOptions))
{
if (directory == null) throw new ArgumentNullException("directory");
if (listener == null) throw new ArgumentNullException("listener");
_directory = directory;
_deadLetterDirectory = new DirectoryInfo(Path.Combine(directory.FullName, "dead"));
_listener = listener;
_autoAcknowledge = options.AutoAcknowledge;
_maxAttempts = options.MaxAttempts <= 0 ? 10 : options.MaxAttempts;
_retryDelay = options.RetryDelay < TimeSpan.Zero ? TimeSpan.Zero : options.RetryDelay;
var concurrencyLimit = options.ConcurrencyLimit <= 0
? QueueOptions.DefaultConcurrencyLimit
: options.ConcurrencyLimit;
_concurrentMessageProcessingSlot = new SemaphoreSlim(concurrencyLimit);
_cancellationTokenSource = new CancellationTokenSource();
_queuedMessages = new BufferBlock<MessageFile>(new DataflowBlockOptions
{
CancellationToken = _cancellationTokenSource.Token
});
}
开发者ID:tdbrian,项目名称:Platibus,代码行数:25,代码来源:FilesystemMessageQueue.cs
示例5: TestCaptureOrder
public void TestCaptureOrder()
{
// post source ints
var intSource = new BufferBlock<int>();
intSource.Post(1);
intSource.Post(2);
intSource.Post(99);
intSource.Post(98);
intSource.Complete();
// capture source order
var orderedInts = OrderingBlock.CaptureOrder<int, long, long>(
intSource, intValue => (long)intValue);
// post longs to combine, in reverse of original order
var longSource = new BufferBlock<long>();
longSource.Post(99);
longSource.Post(98);
longSource.Post(2);
longSource.Post(1);
longSource.Complete();
// apply source order
var orderedLongs = orderedInts.ApplyOrder(longSource, longValue => longValue);
// verify the original order was preserved
CollectionAssert.AreEqual(new long[] { 1, 2, 99, 98 }, orderedLongs.ToEnumerable().ToList());
}
开发者ID:cole2295,项目名称:BitSharp,代码行数:28,代码来源:OrderingBlockTest.cs
示例6: TestUtxoLookAheadWithTransactions
public void TestUtxoLookAheadWithTransactions()
{
var deferredCursor = new Mock<IDeferredChainStateCursor>();
deferredCursor.Setup(x => x.CursorCount).Returns(4);
var blockTxes = new BufferBlock<DecodedBlockTx>();
var lookAhead = UtxoLookAhead.LookAhead(blockTxes, deferredCursor.Object);
var blockTx0 = BlockTx.Create(0, RandomData.RandomTransaction(new RandomDataOptions { TxInputCount = 2 }));
var blockTx1 = BlockTx.Create(1, RandomData.RandomTransaction(new RandomDataOptions { TxInputCount = 2 }));
var blockTx2 = BlockTx.Create(2, RandomData.RandomTransaction(new RandomDataOptions { TxInputCount = 2 }));
blockTxes.Post(blockTx0);
blockTxes.Post(blockTx1);
blockTxes.Post(blockTx2);
blockTxes.Complete();
// verify each transaction was forwarded
var expectedBlockTxes = new[] { blockTx0, blockTx1, blockTx2 };
var warmedTxes = lookAhead.ReceiveAllAsync().Result;
Assert.AreEqual(3, warmedTxes.Count);
CollectionAssert.AreEqual(expectedBlockTxes.Select(x => x.Hash).ToList(), warmedTxes.Select(x => x.Hash).ToList());
// verify each non-coinbase input transaction was warmed up
var expectedLookups = expectedBlockTxes.Skip(1).SelectMany(x => x.Transaction.Inputs.Select(input => input.PrevTxOutputKey.TxHash));
foreach (var txHash in expectedLookups)
deferredCursor.Verify(x => x.WarmUnspentTx(txHash));
Assert.IsTrue(lookAhead.Completion.Wait(2000));
}
开发者ID:cole2295,项目名称:BitSharp,代码行数:31,代码来源:UtxoLookAheadTest.cs
示例7: 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();
}
开发者ID:RePierre,项目名称:dot-net-async,代码行数:26,代码来源:SimpleNetworkExample.cs
示例8: 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);
}
开发者ID:Koulio,项目名称:AsyncOrigoDbSpike,代码行数:30,代码来源:ExecutionPipeline.cs
示例9: HttpNegotiationQueue
public HttpNegotiationQueue(WebSocketFactoryCollection standards, WebSocketConnectionExtensionCollection extensions, WebSocketListenerOptions options)
{
Guard.ParameterCannotBeNull(standards, "standards");
Guard.ParameterCannotBeNull(extensions, "extensions");
Guard.ParameterCannotBeNull(options, "options");
_options = options;
_extensions = extensions;
_cancel = new CancellationTokenSource();
_semaphore = new SemaphoreSlim(options.ParallelNegotiations);
_sockets = new BufferBlock<Socket>(new DataflowBlockOptions()
{
BoundedCapacity = options.NegotiationQueueCapacity,
CancellationToken = _cancel.Token
});
_negotiations = new BufferBlock<WebSocketNegotiationResult>(new DataflowBlockOptions()
{
BoundedCapacity = options.NegotiationQueueCapacity,
CancellationToken = _cancel.Token,
});
_cancel.Token.Register(_sockets.Complete);
_cancel.Token.Register(_negotiations.Complete);
_handShaker = new WebSocketHandshaker(standards, _options);
Task.Run((Func<Task>)WorkAsync);
}
开发者ID:papci,项目名称:WebSocketListener,代码行数:30,代码来源:HttpNegotiationQueue.cs
示例10: 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);
}
开发者ID:nlhepler,项目名称:mono,代码行数:33,代码来源:GreedyTest.cs
示例11: 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());
}
开发者ID:SoftFx,项目名称:PerformancePoC,代码行数:26,代码来源:StringLoggerTest.cs
示例12: 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();
}
开发者ID:mikehadlow,项目名称:Mike.Spikes,代码行数:25,代码来源:DataflowUrlGetter.cs
示例13: TestDataBroadcaster2
public async Task TestDataBroadcaster2()
{
var random = new Random();
var buffer = new BufferBlock<int>();
int sum1 = 0;
int sum2 = 0;
int sum3 = 0;
var action1 = new ActionBlock<int>(i => sum1 = sum1 + i);
var action2 = new ActionBlock<int>(i => sum2 = sum2 + i);
var action3 = new ActionBlock<int>(i => sum3 = sum3 + i);
buffer.ToDataflow().LinkToMultiple(new []{action1, action2, action3}.Select(a => a.ToDataflow()).ToArray());
for (int j = 0; j < 1000; j++)
{
buffer.Post((int)(random.NextDouble() * 10000));
}
buffer.Complete();
await TaskEx.AwaitableWhenAll(action1.Completion, action2.Completion, action3.Completion);
Console.WriteLine("sum1 = {0} , sum2 = {1}", sum1, sum2);
Assert.AreEqual(sum1, sum2);
Assert.AreEqual(sum1, sum3);
}
开发者ID:charles-schrupp,项目名称:DataflowEx,代码行数:28,代码来源:TestDataBroadcaster.cs
示例14: ReceiveCompletedTest
public void ReceiveCompletedTest ()
{
var block = new BufferBlock<int> ();
block.Complete ();
AssertEx.Throws<InvalidOperationException> (
() => block.Receive (TimeSpan.FromMilliseconds (1000)));
}
开发者ID:Profit0004,项目名称:mono,代码行数:7,代码来源:DataflowBlockTest.cs
示例15: 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);
}
开发者ID:carrie901,项目名称:mono,代码行数:26,代码来源:BufferBlockTest.cs
示例16: TestExceptionInLoadTxInput
public void TestExceptionInLoadTxInput()
{
var expectedException = new Exception();
var coreStorage = new Mock<ICoreStorage>();
var chainedHeader = RandomData.RandomChainedHeader();
var tx = RandomData.RandomTransaction(new RandomDataOptions { TxInputCount = 1 });
var txLookupKey = new TxLookupKey(UInt256.Zero, 0);
var loadingTx = new LoadingTx(1, tx, chainedHeader, ImmutableArray.Create(txLookupKey));
var loadingTxes = new BufferBlock<LoadingTx>();
loadingTxes.Post(loadingTx);
loadingTxes.Complete();
// throw expected exception when the input transaction is looked up
Transaction outputTx = null;
coreStorage.Setup(x => x.TryGetTransaction(txLookupKey.BlockHash, txLookupKey.TxIndex, out outputTx)).Throws(expectedException);
var loadedTxes = TxLoader.LoadTxes(coreStorage.Object, loadingTxes);
Exception actualEx;
AssertMethods.AssertAggregateThrows<Exception>(() =>
loadedTxes.ToEnumerable().ToList(), out actualEx);
Assert.AreSame(expectedException, actualEx);
}
开发者ID:ArsenShnurkov,项目名称:BitSharp,代码行数:26,代码来源:TxLoaderTest.cs
示例17: GetLineSplitterBlock
public static IPropagatorBlock<FileLinesEnumerator.FileLine, FileLineWord> GetLineSplitterBlock()
{
var resultsBlock = new BufferBlock<FileLineWord>();
var actionBlock = new ActionBlock<FileLinesEnumerator.FileLine>(
l =>
{
int? wordStart = null;
var endOfProcesssing = false;
for (var col = 1; !endOfProcesssing; ++col)
{
endOfProcesssing = col > l.Line.Length;
var ch = endOfProcesssing ? ' ' : l.Line[col - 1];
if (char.IsLetter(ch))
{
if (!wordStart.HasValue)
{
wordStart = col;
}
}
else if (wordStart.HasValue)
{
resultsBlock.Post(new FileLineWord(
l.File,
l.Line.Substring(wordStart.Value - 1, col - wordStart.Value).ToUpperInvariant(),
l.Row,
wordStart.Value));
wordStart = null;
}
}
},
new ExecutionDataflowBlockOptions { MaxDegreeOfParallelism = Utils.GlobalMaxDegreeOfParallelism });
actionBlock.PropagateCompleted(resultsBlock);
return DataflowBlock.Encapsulate(actionBlock, resultsBlock);
}
开发者ID:eugene-sea,项目名称:FileWordsDataflow,代码行数:35,代码来源:LineSplitter.cs
示例18: 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();
}
开发者ID:RePierre,项目名称:dot-net-async,代码行数:35,代码来源:CompletionExample.cs
示例19: GetFileLinesEnumeratorBlock
public static IPropagatorBlock<File, FileLine> GetFileLinesEnumeratorBlock()
{
var resultsBlock = new BufferBlock<FileLine>();
var actionBlock = new ActionBlock<File>(
async file =>
{
using (var reader = new System.IO.StreamReader(new System.IO.FileStream(
file.FullPath,
System.IO.FileMode.Open,
System.IO.FileAccess.Read,
System.IO.FileShare.Read,
bufferSize: 4096,
useAsync: true)))
{
string line;
var row = 1;
while ((line = await reader.ReadLineAsync()) != null)
{
if (!string.IsNullOrWhiteSpace(line))
{
resultsBlock.Post(new FileLine(file, row, line));
}
row++;
}
}
},
new ExecutionDataflowBlockOptions { MaxDegreeOfParallelism = Utils.GlobalMaxDegreeOfParallelism });
actionBlock.PropagateCompleted(resultsBlock);
return DataflowBlock.Encapsulate(actionBlock, resultsBlock);
}
开发者ID:eugene-sea,项目名称:FileWordsDataflow,代码行数:32,代码来源:FileLinesEnumerator.cs
示例20: WebSocketClient
protected WebSocketClient()
{
_sendBuffer = new BufferBlock<string>(new DataflowBlockOptions
{
BoundedCapacity = 8
});
}
开发者ID:Rohansi,项目名称:RohBot,代码行数:7,代码来源:WebSocketClient.cs
注:本文中的BufferBlock类示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论