Skip to content

Instantly share code, notes, and snippets.

Import-Module WebAdministration
# Timestamp for file
$timestamp = Get-Date -Format "yyyyMMdd_HHmmss"
$basePath = "D:\ServiceHealth\Logs"
# A unique identifier for this run
$jobId = [guid]::NewGuid().ToString()
$records = @()
// Add parallelism with no extra code — just configure the blocks:
var getFolderContents = new TransformManyBlock<string, string>(
folder => Directory.GetFileSystemEntries(folder),
new ExecutionDataflowBlockOptions { MaxDegreeOfParallelism = 4 });
var computeMD5 = new TransformBlock<string, (string FilePath, string Hash)>(
filePath => /* ... */,
new ExecutionDataflowBlockOptions { MaxDegreeOfParallelism = 8 });
string rootFolder = @"C:\Projects\MyApp";
getFolderContents.Post(rootFolder);
getFolderContents.Complete();
await displayResult.Completion;
var linkOptions = new DataflowLinkOptions { PropagateCompletion = true };
// RECURSION: If the entry is a directory, feed it back into the same block.
getFolderContents.LinkTo(getFolderContents, linkOptions,
entry => Directory.Exists(entry));
// BASE CASE: If the entry is a file, send it forward for hashing.
getFolderContents.LinkTo(computeMD5, linkOptions,
entry => File.Exists(entry));
using System.Security.Cryptography;
using System.Threading.Tasks.Dataflow;
// The recursive block: takes a folder path, returns all entries inside it.
// TransformManyBlock is ideal here because one folder produces many entries.
var getFolderContents = new TransformManyBlock<string, string>(folder =>
{
return Directory.GetFileSystemEntries(folder);
});
// Option 1: Always include a catch-all link as shown before
sourceBlock.LinkTo(defaultBlock);
// Option 2: Use NullTarget to discard unmatched messages
sourceBlock.LinkTo(DataflowBlock.NullTarget<Order>());
public class Order
{
public int Id { get; set; }
public decimal Amount { get; set; }
public string Priority { get; set; }
public string Status { get; set; }
}
public class OrderProcessor
{
var sourceBlock = new BufferBlock<string>();
var urgentBlock = new ActionBlock<string>(msg => Console.WriteLine($"URGENT: {msg}"));
var normalBlock = new ActionBlock<string>(msg => Console.WriteLine($"Normal: {msg}"));
var unhandledBlock = new ActionBlock<string>(msg => Console.WriteLine($"Unhandled: {msg}"));
// Specific conditions first
sourceBlock.LinkTo(urgentBlock, new DataflowLinkOptions { PropagateCompletion = true },
msg => msg.StartsWith("URGENT:"));
sourceBlock.LinkTo(normalBlock, new DataflowLinkOptions { PropagateCompletion = true },
using System.Threading.Tasks.Dataflow;
var broadcastBlock = new BroadcastBlock<int>(null);
var evenBlock = new ActionBlock<int>(n =>
Console.WriteLine($"Even: {n}"));
var oddBlock = new ActionBlock<int>(n =>
Console.WriteLine($"Odd: {n}"));
IDisposable LinkTo(
ITargetBlock<TOutput> target,
DataflowLinkOptions linkOptions,
Predicate<TOutput> predicate
)