本文整理汇总了C#中ActionBlock.Complete方法的典型用法代码示例。如果您正苦于以下问题:C# ActionBlock.Complete方法的具体用法?C# ActionBlock.Complete怎么用?C# ActionBlock.Complete使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类ActionBlock
的用法示例。
在下文中一共展示了ActionBlock.Complete方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: Run
public void Run()
{
this.output.WriteLine("TPL start");
this.CheckFileExists();
var f = new FileInfo(this.sampleLogFileName);
this.fileSizeInBytes = f.Length;
this.lineSizeInBytesSoFar = 0;
this.lineCount = 0;
var sw = new Stopwatch();
sw.Start();
var options = new ExecutionDataflowBlockOptions { MaxDegreeOfParallelism = 8 };
var ab = new ActionBlock<string>(s => this.ProcessLine(s), options);
using (TextReader reader = File.OpenText(this.sampleLogFileName))
{
string line;
while ((line = reader.ReadLine()) != null)
{
ab.Post(line);
}
}
ab.Complete();
ab.Completion.Wait();
sw.Stop();
this.ShowResults();
this.output.WriteLine();
this.output.WriteLine("TPL done in {0}", sw.Elapsed);
}
示例2: Engine
public Engine(IWorkItemRepository repository, IActivityRunner activityRunner,
IStateMachineProvider stateMachineProvider)
{
if (repository == null) throw new ArgumentNullException("repository");
if (activityRunner == null) throw new ArgumentNullException("activityRunner");
if (stateMachineProvider == null) throw new ArgumentNullException("stateMachineProvider");
_repository = repository;
_activityRunner = activityRunner;
_stateMachineProvider = stateMachineProvider;
_stateQueue = new ActionBlock<int>(id => UpdateState(id),
new ExecutionDataflowBlockOptions
{
MaxDegreeOfParallelism = 1
});
_workerQueue = new ActionBlock<int>(id => RunActivity(id),
new ExecutionDataflowBlockOptions
{
MaxDegreeOfParallelism = int.MaxValue
});
_stateQueue.Completion.ContinueWith(t => { _workerQueue.Complete(); }, TaskContinuationOptions.OnlyOnFaulted);
_workerQueue.Completion.ContinueWith(t => { ((IDataflowBlock) _stateQueue).Fault(t.Exception); },
TaskContinuationOptions.OnlyOnFaulted);
}
示例3: Configure
public void Configure(string collectorName, XElement configElement, ISystemMetricsService systemMetrics)
{
_log = SuperCheapIOC.Resolve<ILog>();
_systemMetrics = systemMetrics;
var config = new SqlServerConfiguration(configElement.Attribute("connectionString").Value, configElement.ToInt("writeBatchSize"));
_connectionString = config.ConnectionString;
_collectorName = collectorName;
_retries = config.Retries;
InitialiseRetryHandling();
_batchBlock = new BatchBlock<GraphiteLine>(config.WriteBatchSize);
_actionBlock = new ActionBlock<GraphiteLine[]>(p => SendToDB(p), new ExecutionDataflowBlockOptions() { MaxDegreeOfParallelism = 1 });
_batchBlock.LinkTo(_actionBlock);
_batchBlock.Completion.ContinueWith(p => _actionBlock.Complete());
_actionBlock.Completion.ContinueWith(p => { _isActive = false; });
_completionTask = new Task(() =>
{
_log.Info("SqlServerBackend - Completion has been signaled. Waiting for action block to complete.");
_batchBlock.Complete();
_actionBlock.Completion.Wait();
});
}
示例4: Run
public override void Run(bool runChildren)
{
DataRowBlock = new ActionBlock<DataRowObject>((n) => NextDataRow(n));
SetEndAction(() => {
DataRowBlock.Complete();
DataRowBlock.Completion.Wait();
});
base.Run(runChildren);
}
示例5: TestPost
public void TestPost()
{
foreach (bool bounded in DataflowTestHelpers.BooleanValues)
{
ActionBlock<int> ab = new ActionBlock<int>(i => { },
new ExecutionDataflowBlockOptions { BoundedCapacity = bounded ? 1 : -1 }); // test greedy and then non-greedy
Assert.True(ab.Post(0), "Expected non-completed ActionBlock to accept Post'd message");
ab.Complete();
Assert.False(ab.Post(0), "Expected Complete'd ActionBlock to decline messages");
}
}
示例6: ProcessingByTPL_StraightForwardImplementation
static public void ProcessingByTPL_StraightForwardImplementation()
{
const string pathToFiles = @"..\..\..\..\DataFiles";
string[] files = Directory.GetFiles(pathToFiles, "*.txt", SearchOption.AllDirectories);
var loadDataFromFileBlock = new TransformBlock<string[], List<CustomerTextData>>(fileItems =>
{
var factory = new CustomerTextDataFactory();
return new List<CustomerTextData>(Array.ConvertAll(fileItems, factory.LoadFromFile));
});
var filterBlock = new TransformBlock<List<CustomerTextData>, List<CustomerTextData>>(textDataList =>
{
var filter = new FilterTextData(5);
return textDataList.Where(filter.Run).ToList();
});
var toListBlock = new TransformManyBlock<List<CustomerTextData>, CustomerTextData>(textDataList =>
{
var queue = new ConcurrentQueue<CustomerTextData>();
textDataList.ForEach(queue.Enqueue);
return queue;
});
var action = new ActionBlock<CustomerTextData>(textData =>
{
var weight = new WeightTextData();
int result = weight.Run(textData);
Trace.WriteLine(result);
Console.WriteLine(result);
});
loadDataFromFileBlock.LinkTo(filterBlock);
filterBlock.LinkTo(toListBlock);
toListBlock.LinkTo(action);
loadDataFromFileBlock.Completion.ContinueWith(t =>
{
if (t.IsFaulted) ((IDataflowBlock)filterBlock).Fault(t.Exception);
else filterBlock.Complete();
});
filterBlock.Completion.ContinueWith(t =>
{
if (t.IsFaulted) ((IDataflowBlock)toListBlock).Fault(t.Exception);
else toListBlock.Complete();
});
toListBlock.Completion.ContinueWith(t =>
{
if (t.IsFaulted) ((IDataflowBlock)action).Fault(t.Exception);
else action.Complete();
});
loadDataFromFileBlock.Post(files);
loadDataFromFileBlock.Complete();
action.Completion.Wait();
}
示例7: CompleteTest
public void CompleteTest ()
{
var block = new ActionBlock<int> (i => Thread.Sleep (100));
for (int i = 0; i < 10; i++)
Assert.IsTrue (block.Post (i), "Not Accepted");
block.Complete ();
// Still element to be processed so Completion should be false
Assert.IsFalse (block.Completion.IsCompleted);
block.Completion.Wait ();
Assert.IsTrue (block.Completion.IsCompleted);
}
示例8: AsyncNullTest
public void AsyncNullTest()
{
var scheduler = new TestScheduler ();
var block = new ActionBlock<int> (
i => null,
new ExecutionDataflowBlockOptions { TaskScheduler = scheduler });
Assert.IsTrue (block.Post (1));
scheduler.ExecuteAll ();
Assert.IsFalse (block.Completion.Wait (100));
block.Complete ();
Assert.IsTrue (block.Completion.Wait (100));
}
示例9: TransformThroughFilterToAction
internal static bool TransformThroughFilterToAction()
{
const int ITERS = 2;
int completedCount = 0;
var t = new TransformBlock<int, int>(i => i);
var c = new ActionBlock<int>(i => completedCount++);
t.LinkTo(c, i => true);
t.Completion.ContinueWith(_ => c.Complete());
for (int i = 0; i < ITERS; i++) t.Post(i);
t.Complete();
c.Completion.Wait();
return completedCount == ITERS;
}
示例10: ProduceLogs
public void ProduceLogs(int count, int buffSize)
{
var options = new ExecutionDataflowBlockOptions() { BoundedCapacity = buffSize, MaxDegreeOfParallelism = 1, SingleProducerConstrained = true };
LogGenerator g = new LogGenerator();
var file = new StreamWriter("basic.async.log", false);
ActionBlock<string> writer = new ActionBlock<string>(s => file.WriteLine(s), options);
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();
}
writer.Complete();
Completed = writer.Completion.ContinueWith(t => file.Close());
}
示例11: TestReleasingOfPostponedMessages
//[Fact(Skip = "Outerloop")]
public void TestReleasingOfPostponedMessages()
{
const int excess = 5;
for (int dop = 1; dop <= Parallelism.ActualDegreeOfParallelism; dop++)
{
var localPassed = true;
var nextOfferEvent = new AutoResetEvent(true);
var releaseProcessingEvent = new ManualResetEventSlim();
var options = new ExecutionDataflowBlockOptions { MaxDegreeOfParallelism = dop, BoundedCapacity = dop };
var action = new ActionBlock<int>(x => { nextOfferEvent.Set(); releaseProcessingEvent.Wait(); }, options);
var sendAsyncDop = new Task<bool>[dop];
var sendAsyncExcess = new Task<bool>[excess];
// Send DOP messages
for (int i = 0; i < dop; i++)
{
// Throttle sending to make sure we saturate DOP exactly
nextOfferEvent.WaitOne();
sendAsyncDop[i] = action.SendAsync(i);
}
// Send EXCESS more messages. All of these will surely be postponed
for (int i = 0; i < excess; i++)
sendAsyncExcess[i] = action.SendAsync(dop + i);
// Wait until the tasks for the first DOP messages get completed
Task.WaitAll(sendAsyncDop, 5000);
// Complete the block. This will cause the EXCESS messages to be declined.
action.Complete();
releaseProcessingEvent.Set();
// Verify all DOP messages have been accepted
for (int i = 0; i < dop; i++) localPassed &= sendAsyncDop[i].Result;
Assert.True(localPassed, string.Format("DOP={0} : Consumed up to DOP - {1}", dop, localPassed ? "Passed" : "FAILED"));
// Verify all EXCESS messages have been declined
localPassed = true;
for (int i = 0; i < excess; i++) localPassed &= !sendAsyncExcess[i].Result;
Assert.True(localPassed, string.Format("DOP={0} : Declined excess - {1}", dop, localPassed ? "Passed" : "FAILED"));
}
}
示例12: ConvertToCsvLines
private static IEnumerable<string> ConvertToCsvLines(IEnumerable<CloudBlockBlob> blobs, int maxDegreeOfParallelism)
{
var lines = new BlockingCollection<string>(BoundedCapacity);
Task.Run(async () =>
{
var actionBlock = new ActionBlock<CloudBlockBlob>(
async (b) =>
{
var line = await ConvertToCsvLineAsync(b);
lines.Add(line);
},
new ExecutionDataflowBlockOptions { MaxDegreeOfParallelism = maxDegreeOfParallelism });
foreach (var blob in blobs)
{
var postSuccess = actionBlock.Post(blob);
}
actionBlock.Complete();
await actionBlock.Completion;
lines.CompleteAdding();
});
return lines.GetConsumingEnumerable();
}
示例13: Main
static void Main(string[] args)
{
//
// Create the members of the pipeline.
//
// Downloads the requested resource as a string.
var downloadString = new TransformBlock<string, string>(uri =>
{
Console.WriteLine("Downloading '{0}'...", uri);
return new WebClient().DownloadString(uri);
});
// Separates the specified text into an array of words.
var createWordList = new TransformBlock<string, string[]>(text =>
{
Console.WriteLine("Creating word list...");
// Remove common punctuation by replacing all non-letter characters
// with a space character to.
char[] tokens = text.ToArray();
for (int i = 0; i < tokens.Length; i++)
{
if (!char.IsLetter(tokens[i]))
tokens[i] = ' ';
}
text = new string(tokens);
// Separate the text into an array of words.
return text.Split(new char[] { ' ' },
StringSplitOptions.RemoveEmptyEntries);
});
// Removes short words, orders the resulting words alphabetically,
// and then remove duplicates.
var filterWordList = new TransformBlock<string[], string[]>(words =>
{
Console.WriteLine("Filtering word list...");
return words.Where(word => word.Length > 3).OrderBy(word => word)
.Distinct().ToArray();
});
// Finds all words in the specified collection whose reverse also
// exists in the collection.
var findReversedWords = new TransformManyBlock<string[], string>(words =>
{
Console.WriteLine("Finding reversed words...");
// Holds reversed words.
var reversedWords = new ConcurrentQueue<string>();
// Add each word in the original collection to the result whose
// reversed word also exists in the collection.
Parallel.ForEach(words, word =>
{
// Reverse the work.
string reverse = new string(word.Reverse().ToArray());
// Enqueue the word if the reversed version also exists
// in the collection.
if (Array.BinarySearch<string>(words, reverse) >= 0 &&
word != reverse)
{
reversedWords.Enqueue(word);
}
});
return reversedWords;
});
// Prints the provided reversed words to the console.
var printReversedWords = new ActionBlock<string>(reversedWord =>
{
Console.WriteLine("Found reversed words {0}/{1}",
reversedWord, new string(reversedWord.Reverse().ToArray()));
});
//
// Connect the dataflow blocks to form a pipeline.
//
downloadString.LinkTo(createWordList);
createWordList.LinkTo(filterWordList);
filterWordList.LinkTo(findReversedWords);
findReversedWords.LinkTo(printReversedWords);
//
// For each completion task in the pipeline, create a continuation task
// that marks the next block in the pipeline as completed.
// A completed dataflow block processes any buffered elements, but does
// not accept new elements.
//
downloadString.Completion.ContinueWith(t =>
{
if (t.IsFaulted) ((IDataflowBlock)createWordList).Fault(t.Exception);
else createWordList.Complete();
});
//.........这里部分代码省略.........
示例14: Compress
public static async Task Compress(Stream inputStream, Stream outputStream)
{
var buffer = new BufferBlock<CompressionDetails>(new DataflowBlockOptions { BoundedCapacity = BoundedCapacity });
var compressorOptions = new ExecutionDataflowBlockOptions
{
MaxDegreeOfParallelism = MaxDegreeOfParallelism,
BoundedCapacity = BoundedCapacity
};
var writerOptions = new ExecutionDataflowBlockOptions
{
BoundedCapacity = BoundedCapacity,
SingleProducerConstrained = true
};
var compressor = new TransformBlock<CompressionDetails, CompressionDetails>(compressionDetails => Compress(compressionDetails), compressorOptions);
var writer = new ActionBlock<CompressionDetails>(compressionDetailsWithSize => Multiplex(outputStream, compressionDetailsWithSize), writerOptions);
buffer.LinkTo(compressor);
compressor.LinkTo(writer);
buffer.Completion.ContinueWith(task => compressor.Complete());
compressor.Completion.ContinueWith(task => writer.Complete());
long sourceLength = inputStream.Length;
// Write total size to destination
byte[] size = BitConverter.GetBytes(sourceLength);
await outputStream.WriteAsync(size, 0, size.Length);
long chunkSize = 1048576; // 1 MB
int index = 0;
while (sourceLength > 0)
{
byte[] data = new byte[chunkSize];
int readCount = await inputStream.ReadAsync(data, 0, data.Length);
byte[] bytes = new byte[readCount];
Buffer.BlockCopy(data, 0, bytes, 0, readCount);
CompressionDetails compressionDetails = new CompressionDetails
{
Bytes = bytes,
ChunkSize = BitConverter.GetBytes(chunkSize),
Sequence = ++index
};
while (await buffer.SendAsync(compressionDetails) != true) { }
sourceLength -= chunkSize;
if (sourceLength < chunkSize)
chunkSize = sourceLength;
if (sourceLength == 0)
buffer.Complete();
}
writer.Completion.Wait();
await outputStream.FlushAsync();
inputStream.Dispose();
outputStream.Dispose();
}
示例15: WriteOnceToAction
internal static bool WriteOnceToAction()
{
const int ITERS = 2;
int completedCount = 0;
var c = new ActionBlock<int>(i => completedCount++);
var singleAssignments = Enumerable.Range(0, ITERS).Select(_ =>
{
var s = new WriteOnceBlock<int>(i => i);
s.LinkTo(c);
return s;
}).ToList();
Task.Factory.ContinueWhenAll(singleAssignments.Select(s => s.Completion).ToArray(), _ => c.Complete());
foreach (var s in singleAssignments) s.Post(1);
c.Completion.Wait();
return completedCount == ITERS;
}