Parallel work and a console do not mix on their own: every thread that writes to the console writes over the others. ConsoleMonster gives the screen to one thread and lets every other thread send it updates, so a live view stays whole however many workers report to it, and output that is not a terminal gets whole lines in order. The guarantees at the end sum up what it promises.
Twelve threads, one console
Each worker writes its progress with Write-Host as it goes. The pieces of different workers land in each other's lines.
... done web03 swappingweb07 swapping ... done ... done web11 swappingweb02 swapping ... done web09 swapping ... done web08 starting ... done ... done ... done web10 swappingweb03 startingweb06 swapping ... done web01 swapping ... done web07 starting ... done ... done web05 startingweb12 swapping ... done ... done web06 starting ... done web04 swapping ... done web10 starting ... done web11 starting ... done ... done web09 startingweb02 starting ... done web04 starting ... done ... done web01 starting ... done
Install-Module ConsoleMonster -Scope CurrentUser# Twelve servers patched in parallel, each writing its progress straight to the console (PowerShell 7).
$servers = 1..12 | ForEach-Object { 'web{0:d2}' -f $_ }
$servers | ForEach-Object -ThrottleLimit 12 -Parallel {
foreach ($step in 'copying', 'stopping', 'swapping', 'starting') {
Write-Host "$_ $step" -NoNewline
Start-Sleep -Milliseconds (Get-Random -Minimum 40 -Maximum 240)
Write-Host ' ... done'
}
}Run: pwsh ./threads-naive.ps1
dotnet new console -n Threads
cd Threads
dotnet add package ConsoleMonster// Twelve servers patched in parallel, each writing its progress straight to the console.
string[] servers = Enumerable.Range(1, 12).Select(n => $"web{n:00}").ToArray();
string[] steps = { "copying", "stopping", "swapping", "starting" };
await Parallel.ForEachAsync(
servers,
new ParallelOptions { MaxDegreeOfParallelism = 12 },
async (server, token) => {
foreach (string step in steps) {
Console.Write($"{server} {step}");
await Task.Delay(Random.Shared.Next(40, 240), token);
Console.WriteLine(" ... done");
}
});Full program
// Twelve servers patched in parallel, each writing its progress straight to the console.
string[] servers = Enumerable.Range(1, 12).Select(n => $"web{n:00}").ToArray();
string[] steps = { "copying", "stopping", "swapping", "starting" };
await Parallel.ForEachAsync(
servers,
new ParallelOptions { MaxDegreeOfParallelism = 12 },
async (server, token) => {
foreach (string step in steps) {
Console.Write($"{server} {step}");
await Task.Delay(Random.Shared.Next(40, 240), token);
Console.WriteLine(" ... done");
}
});Run: dotnet run
The recording ran the PowerShell script. This C# program does the same with the library and compiles as shown; its timings are its own.
dotnet new console -n Threads
cd Threads
dotnet add package ConsoleMonster// Twelve servers patched in parallel, each writing its progress straight to the console.
string[] servers = Enumerable.Range(1, 12).Select(n => $"web{n:00}").ToArray();
string[] steps = { "copying", "stopping", "swapping", "starting" };
await Parallel.ForEachAsync(
servers,
new ParallelOptions { MaxDegreeOfParallelism = 12 },
async (server, token) => {
foreach (string step in steps) {
Console.Write($"{server} {step}");
await Task.Delay(Random.Shared.Next(40, 240), token);
Console.WriteLine(" ... done");
}
});
Full program
// Twelve servers patched in parallel, each writing its progress straight to the console.
string[] servers = Enumerable.Range(1, 12).Select(n => $"web{n:00}").ToArray();
string[] steps = { "copying", "stopping", "swapping", "starting" };
await Parallel.ForEachAsync(
servers,
new ParallelOptions { MaxDegreeOfParallelism = 12 },
async (server, token) => {
foreach (string step in steps) {
Console.Write($"{server} {step}");
await Task.Delay(Random.Shared.Next(40, 240), token);
Console.WriteLine(" ... done");
}
});
Run: dotnet run
The recording ran the PowerShell script. This C# program does the same with the library and compiles as shown; its timings are its own.
The same work through a dashboard
Each runspace updates its own lane by key and Write-Host goes to the log panel. The session draws the screen about 15 times a second from one thread.
Patching the web farm 00:00:00 ╭─ Servers ─────────────────────────────────────────────────────────────────────────── 12 at once ─╮ │ ✓ web01 ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 100% ✓ 4 ✗ 0 ▲ 0 done in 550ms │ │ ✓ web02 ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 100% ✓ 4 ✗ 0 ▲ 0 done in 588ms │ │ ✓ web03 ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 100% ✓ 4 ✗ 0 ▲ 0 done in 635ms │ │ ✓ web04 ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 100% ✓ 4 ✗ 0 ▲ 0 done in 619ms │ │ ✓ web05 ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 100% ✓ 4 ✗ 0 ▲ 0 done in 631ms │ │ ✓ web06 ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 100% ✓ 4 ✗ 0 ▲ 0 done in 564ms │ │ ⠧ web07 ━━━━━━━━━━━━━━━━━━━━━━━──────── 75% ✓ 3 ✗ 0 ▲ 0 starting │ │ ✓ web08 ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 100% ✓ 4 ✗ 0 ▲ 0 done in 642ms │ │ ⠏ web09 ━━━━━━━━━━━━━━━╸─────────────── 50% ✓ 2 ✗ 0 ▲ 0 swapping │ │ ⠋ web10 ━━━━━━━━━━━━━━━━━━━━━━━──────── 75% ✓ 3 ✗ 0 ▲ 0 starting │ │ ⠙ web11 ━━━━━━━━━━━━━━━╸─────────────── 50% ✓ 2 ✗ 0 ▲ 0 swapping │ │ ⠹ web12 ━━━━━━━━━━━━━━━╸─────────────── 50% ✓ 2 ✗ 0 ▲ 0 swapping │ ╰──────────────────────────────────────────────────────────────────────────────────────────────────╯ ╭─ Log ────────────────────────────────────────────────────────────────────────────────────────────╮ │ 00:00 web03 done │ │ 00:00 web05 done │ │ 00:00 web08 done │ ╰──────────────────────────────────────────────────────────────────────────────────────────────────╯ ctrl+c stop
Install-Module ConsoleMonster -Scope CurrentUser# The same twelve servers, each runspace updating its own lane; Write-Host from any of them goes to the log panel.
$servers = 1..12 | ForEach-Object { 'web{0:d2}' -f $_ }
$dashboard = New-ConsoleDashboard -Title 'Patching the web farm' -Content {
New-ConsolePanel -Title 'Servers' -HeaderRight '12 at once' -Content {
New-ConsoleLanes -WidgetId servers -Content {
foreach ($server in $servers) { @{ Key = $server; Total = 4 } }
}
}
New-ConsolePanel -Title 'Log' -Fill -Content { New-ConsoleLogRegion }
}
$servers | Invoke-ConsoleDashboard $dashboard -Parallel -ThrottleLimit 12 {
param($Server)
foreach ($step in 'copying', 'stopping', 'swapping', 'starting') {
Update-Console -WidgetId servers -Key $Server -Status Running -Detail $step
Start-Sleep -Milliseconds (Get-Random -Minimum 40 -Maximum 240)
Update-Console -WidgetId servers -Key $Server -Result Pass
}
Write-Host "$Server done"
Update-Console -WidgetId servers -Key $Server -Complete
}Full program
Import-Module ConsoleMonster
# The same twelve servers, each runspace updating its own lane; Write-Host from any of them goes to the log panel.
$servers = 1..12 | ForEach-Object { 'web{0:d2}' -f $_ }
$dashboard = New-ConsoleDashboard -Title 'Patching the web farm' -Content {
New-ConsolePanel -Title 'Servers' -HeaderRight '12 at once' -Content {
New-ConsoleLanes -WidgetId servers -Content {
foreach ($server in $servers) { @{ Key = $server; Total = 4 } }
}
}
New-ConsolePanel -Title 'Log' -Fill -Content { New-ConsoleLogRegion }
}
$servers | Invoke-ConsoleDashboard $dashboard -Parallel -ThrottleLimit 12 {
param($Server)
foreach ($step in 'copying', 'stopping', 'swapping', 'starting') {
Update-Console -WidgetId servers -Key $Server -Status Running -Detail $step
Start-Sleep -Milliseconds (Get-Random -Minimum 40 -Maximum 240)
Update-Console -WidgetId servers -Key $Server -Result Pass
}
Write-Host "$Server done"
Update-Console -WidgetId servers -Key $Server -Complete
}Run: pwsh ./threads-dashboard.ps1
dotnet new console -n ThreadsDashboard
cd ThreadsDashboard
dotnet add package ConsoleMonster// The same twelve servers, each worker updating its own lane through a handle; Console.WriteLine from any of them
// goes to the log panel.
string[] servers = Enumerable.Range(1, 12).Select(n => $"web{n:00}").ToArray();
string[] steps = { "copying", "stopping", "swapping", "starting" };
Lanes lanes = new Lanes();
Dashboard dashboard = Ui.Dashboard().Title("Patching the web farm")
.Content(body => body
.Panel(new Panel(lanes, "Servers") { HeaderRight = "12 at once" })
.Add(new Panel(new LogRegion(), "Log").Fill()));
foreach (string server in servers)
{
lanes.Add(server, server, steps.Length);
}
using (LiveSession session = new LiveSession(dashboard))
{
await session.RunAsync(async (s, cancel) =>
{
LanesHandle handle = lanes.Handle(s);
try
{
await Parallel.ForEachAsync(
servers,
new ParallelOptions { MaxDegreeOfParallelism = 12, CancellationToken = cancel },
async (server, token) =>
{
foreach (string step in steps)
{
handle.Start(server, step);
await Task.Delay(Random.Shared.Next(40, 240), token);
handle.Advance(server, StatusKind.Pass);
}
Console.WriteLine(server + " done");
handle.Complete(server);
});
}
catch (OperationCanceledException)
{
// Ctrl+C: the session has already stopped the view; the workers just stop.
}
});
}Full program
using ConsoleMonster;
using ConsoleMonster.Layout;
using ConsoleMonster.Live;
using ConsoleMonster.Styling;
using ConsoleMonster.Widgets;
// The same twelve servers, each worker updating its own lane through a handle; Console.WriteLine from any of them
// goes to the log panel.
string[] servers = Enumerable.Range(1, 12).Select(n => $"web{n:00}").ToArray();
string[] steps = { "copying", "stopping", "swapping", "starting" };
Lanes lanes = new Lanes();
Dashboard dashboard = Ui.Dashboard().Title("Patching the web farm")
.Content(body => body
.Panel(new Panel(lanes, "Servers") { HeaderRight = "12 at once" })
.Add(new Panel(new LogRegion(), "Log").Fill()));
foreach (string server in servers)
{
lanes.Add(server, server, steps.Length);
}
using (LiveSession session = new LiveSession(dashboard))
{
await session.RunAsync(async (s, cancel) =>
{
LanesHandle handle = lanes.Handle(s);
try
{
await Parallel.ForEachAsync(
servers,
new ParallelOptions { MaxDegreeOfParallelism = 12, CancellationToken = cancel },
async (server, token) =>
{
foreach (string step in steps)
{
handle.Start(server, step);
await Task.Delay(Random.Shared.Next(40, 240), token);
handle.Advance(server, StatusKind.Pass);
}
Console.WriteLine(server + " done");
handle.Complete(server);
});
}
catch (OperationCanceledException)
{
// Ctrl+C: the session has already stopped the view; the workers just stop.
}
});
}Run: dotnet run
The recording ran the PowerShell script. This C# program does the same with the library and compiles as shown; its timings are its own.
dotnet new console -n ThreadsDashboard
cd ThreadsDashboard
dotnet add package ConsoleMonster// The same twelve servers, each worker updating its own lane through a handle; Console.WriteLine from any of them
// goes to the log panel.
string[] servers = Enumerable.Range(1, 12).Select(n => $"web{n:00}").ToArray();
string[] steps = { "copying", "stopping", "swapping", "starting" };
Lanes lanes = Ui.Lanes();
Dashboard dashboard = Ui.Dashboard()
.Title("Patching the web farm")
.Content(body => body.Panel(Ui.Panel()
.Title("Servers")
.HeaderRight("12 at once")
.Content(panelContent =>
{
panelContent.Add(lanes);
})).Add(Ui.Panel().Title("Log").Content(panelContent =>
{
panelContent.LogRegion();
}).Fill()));
foreach (string server in servers)
{
lanes.Add(server, server, steps.Length);
}
using (LiveSession session = dashboard.CreateSession())
{
await session.RunAsync(async (s, cancel) =>
{
LanesHandle handle = lanes.Handle(s);
try
{
await Parallel.ForEachAsync(
servers,
new ParallelOptions { MaxDegreeOfParallelism = 12, CancellationToken = cancel },
async (server, token) =>
{
foreach (string step in steps)
{
handle.Start(server, step);
await Task.Delay(Random.Shared.Next(40, 240), token);
handle.Advance(server, StatusKind.Pass);
}
Console.WriteLine(server + " done");
handle.Complete(server);
});
}
catch (OperationCanceledException)
{
// Ctrl+C: the session has already stopped the view; the workers just stop.
}
});
}
Full program
using ConsoleMonster;
using ConsoleMonster.Layout;
using ConsoleMonster.Live;
using ConsoleMonster.Styling;
using ConsoleMonster.Widgets;
// The same twelve servers, each worker updating its own lane through a handle; Console.WriteLine from any of them
// goes to the log panel.
string[] servers = Enumerable.Range(1, 12).Select(n => $"web{n:00}").ToArray();
string[] steps = { "copying", "stopping", "swapping", "starting" };
Lanes lanes = Ui.Lanes();
Dashboard dashboard = Ui.Dashboard()
.Title("Patching the web farm")
.Content(body => body.Panel(Ui.Panel()
.Title("Servers")
.HeaderRight("12 at once")
.Content(panelContent =>
{
panelContent.Add(lanes);
})).Add(Ui.Panel().Title("Log").Content(panelContent =>
{
panelContent.LogRegion();
}).Fill()));
foreach (string server in servers)
{
lanes.Add(server, server, steps.Length);
}
using (LiveSession session = dashboard.CreateSession())
{
await session.RunAsync(async (s, cancel) =>
{
LanesHandle handle = lanes.Handle(s);
try
{
await Parallel.ForEachAsync(
servers,
new ParallelOptions { MaxDegreeOfParallelism = 12, CancellationToken = cancel },
async (server, token) =>
{
foreach (string step in steps)
{
handle.Start(server, step);
await Task.Delay(Random.Shared.Next(40, 240), token);
handle.Advance(server, StatusKind.Pass);
}
Console.WriteLine(server + " done");
handle.Complete(server);
});
}
catch (OperationCanceledException)
{
// Ctrl+C: the session has already stopped the view; the workers just stop.
}
});
}
Run: dotnet run
The recording ran the PowerShell script. This C# program does the same with the library and compiles as shown; its timings are its own.
See also: Invoke-ConsoleDashboard
The same script in CI
With CI detected, the same dashboard writes a whole line for each lane start and finish and each log entry instead of redrawing, in the order the updates were applied, then prints its final state.
[00:00] web10 started [00:00] web07 done [00:00] web07 PASS: 4 passed, 0 failed, 0 warnings in 609ms [00:00] web03 started [00:00] web08 done [00:00] web06 started [00:00] web08 PASS: 4 passed, 0 failed, 0 warnings in 618ms [00:00] web12 started [00:00] web02 started [00:00] web11 started [00:00] web05 started [00:00] web03 done [00:00] web03 PASS: 4 passed, 0 failed, 0 warnings in 772ms [00:00] web09 started [00:00] web01 done [00:00] web01 PASS: 4 passed, 0 failed, 0 warnings in 839ms [00:00] web09 done [00:00] web06 done [00:00] web06 PASS: 4 passed, 0 failed, 0 warnings in 828ms [00:00] web09 PASS: 4 passed, 0 failed, 0 warnings in 782ms [00:00] web11 done [00:00] web11 PASS: 4 passed, 0 failed, 0 warnings in 792ms [00:00] web10 started [00:00] web02 done [00:00] web02 PASS: 4 passed, 0 failed, 0 warnings in 879ms [00:00] web12 done [00:00] web04 started [00:00] web12 PASS: 4 passed, 0 failed, 0 warnings in 807ms [00:00] web05 done
Install-Module ConsoleMonster -Scope CurrentUser# The same twelve servers, each runspace updating its own lane; Write-Host from any of them goes to the log panel.
$servers = 1..12 | ForEach-Object { 'web{0:d2}' -f $_ }
$dashboard = New-ConsoleDashboard -Title 'Patching the web farm' -Content {
New-ConsolePanel -Title 'Servers' -HeaderRight '12 at once' -Content {
New-ConsoleLanes -WidgetId servers -Content {
foreach ($server in $servers) { @{ Key = $server; Total = 4 } }
}
}
New-ConsolePanel -Title 'Log' -Fill -Content { New-ConsoleLogRegion }
}
$servers | Invoke-ConsoleDashboard $dashboard -Parallel -ThrottleLimit 12 {
param($Server)
foreach ($step in 'copying', 'stopping', 'swapping', 'starting') {
Update-Console -WidgetId servers -Key $Server -Status Running -Detail $step
Start-Sleep -Milliseconds (Get-Random -Minimum 40 -Maximum 240)
Update-Console -WidgetId servers -Key $Server -Result Pass
}
Write-Host "$Server done"
Update-Console -WidgetId servers -Key $Server -Complete
}Full program
Import-Module ConsoleMonster
# The same twelve servers, each runspace updating its own lane; Write-Host from any of them goes to the log panel.
$servers = 1..12 | ForEach-Object { 'web{0:d2}' -f $_ }
$dashboard = New-ConsoleDashboard -Title 'Patching the web farm' -Content {
New-ConsolePanel -Title 'Servers' -HeaderRight '12 at once' -Content {
New-ConsoleLanes -WidgetId servers -Content {
foreach ($server in $servers) { @{ Key = $server; Total = 4 } }
}
}
New-ConsolePanel -Title 'Log' -Fill -Content { New-ConsoleLogRegion }
}
$servers | Invoke-ConsoleDashboard $dashboard -Parallel -ThrottleLimit 12 {
param($Server)
foreach ($step in 'copying', 'stopping', 'swapping', 'starting') {
Update-Console -WidgetId servers -Key $Server -Status Running -Detail $step
Start-Sleep -Milliseconds (Get-Random -Minimum 40 -Maximum 240)
Update-Console -WidgetId servers -Key $Server -Result Pass
}
Write-Host "$Server done"
Update-Console -WidgetId servers -Key $Server -Complete
}Run: $env:CI = 'true'; pwsh ./threads-dashboard.ps1; Remove-Item Env:CI
// The same twelve servers, each worker updating its own lane through a handle; Console.WriteLine from any of them
// goes to the log panel.
string[] servers = Enumerable.Range(1, 12).Select(n => $"web{n:00}").ToArray();
string[] steps = { "copying", "stopping", "swapping", "starting" };
Lanes lanes = new Lanes();
Dashboard dashboard = Ui.Dashboard().Title("Patching the web farm")
.Content(body => body
.Panel(new Panel(lanes, "Servers") { HeaderRight = "12 at once" })
.Add(new Panel(new LogRegion(), "Log").Fill()));
foreach (string server in servers)
{
lanes.Add(server, server, steps.Length);
}
using (LiveSession session = new LiveSession(dashboard))
{
await session.RunAsync(async (s, cancel) =>
{
LanesHandle handle = lanes.Handle(s);
try
{
await Parallel.ForEachAsync(
servers,
new ParallelOptions { MaxDegreeOfParallelism = 12, CancellationToken = cancel },
async (server, token) =>
{
foreach (string step in steps)
{
handle.Start(server, step);
await Task.Delay(Random.Shared.Next(40, 240), token);
handle.Advance(server, StatusKind.Pass);
}
Console.WriteLine(server + " done");
handle.Complete(server);
});
}
catch (OperationCanceledException)
{
// Ctrl+C: the session has already stopped the view; the workers just stop.
}
});
}Full program
using ConsoleMonster;
using ConsoleMonster.Layout;
using ConsoleMonster.Live;
using ConsoleMonster.Styling;
using ConsoleMonster.Widgets;
// The same twelve servers, each worker updating its own lane through a handle; Console.WriteLine from any of them
// goes to the log panel.
string[] servers = Enumerable.Range(1, 12).Select(n => $"web{n:00}").ToArray();
string[] steps = { "copying", "stopping", "swapping", "starting" };
Lanes lanes = new Lanes();
Dashboard dashboard = Ui.Dashboard().Title("Patching the web farm")
.Content(body => body
.Panel(new Panel(lanes, "Servers") { HeaderRight = "12 at once" })
.Add(new Panel(new LogRegion(), "Log").Fill()));
foreach (string server in servers)
{
lanes.Add(server, server, steps.Length);
}
using (LiveSession session = new LiveSession(dashboard))
{
await session.RunAsync(async (s, cancel) =>
{
LanesHandle handle = lanes.Handle(s);
try
{
await Parallel.ForEachAsync(
servers,
new ParallelOptions { MaxDegreeOfParallelism = 12, CancellationToken = cancel },
async (server, token) =>
{
foreach (string step in steps)
{
handle.Start(server, step);
await Task.Delay(Random.Shared.Next(40, 240), token);
handle.Advance(server, StatusKind.Pass);
}
Console.WriteLine(server + " done");
handle.Complete(server);
});
}
catch (OperationCanceledException)
{
// Ctrl+C: the session has already stopped the view; the workers just stop.
}
});
}The recording ran the PowerShell script. This C# program does the same with the library and compiles as shown; its timings are its own.
// The same twelve servers, each worker updating its own lane through a handle; Console.WriteLine from any of them
// goes to the log panel.
string[] servers = Enumerable.Range(1, 12).Select(n => $"web{n:00}").ToArray();
string[] steps = { "copying", "stopping", "swapping", "starting" };
Lanes lanes = Ui.Lanes();
Dashboard dashboard = Ui.Dashboard()
.Title("Patching the web farm")
.Content(body => body.Panel(Ui.Panel()
.Title("Servers")
.HeaderRight("12 at once")
.Content(panelContent =>
{
panelContent.Add(lanes);
})).Add(Ui.Panel().Title("Log").Content(panelContent =>
{
panelContent.LogRegion();
}).Fill()));
foreach (string server in servers)
{
lanes.Add(server, server, steps.Length);
}
using (LiveSession session = dashboard.CreateSession())
{
await session.RunAsync(async (s, cancel) =>
{
LanesHandle handle = lanes.Handle(s);
try
{
await Parallel.ForEachAsync(
servers,
new ParallelOptions { MaxDegreeOfParallelism = 12, CancellationToken = cancel },
async (server, token) =>
{
foreach (string step in steps)
{
handle.Start(server, step);
await Task.Delay(Random.Shared.Next(40, 240), token);
handle.Advance(server, StatusKind.Pass);
}
Console.WriteLine(server + " done");
handle.Complete(server);
});
}
catch (OperationCanceledException)
{
// Ctrl+C: the session has already stopped the view; the workers just stop.
}
});
}
Full program
using ConsoleMonster;
using ConsoleMonster.Layout;
using ConsoleMonster.Live;
using ConsoleMonster.Styling;
using ConsoleMonster.Widgets;
// The same twelve servers, each worker updating its own lane through a handle; Console.WriteLine from any of them
// goes to the log panel.
string[] servers = Enumerable.Range(1, 12).Select(n => $"web{n:00}").ToArray();
string[] steps = { "copying", "stopping", "swapping", "starting" };
Lanes lanes = Ui.Lanes();
Dashboard dashboard = Ui.Dashboard()
.Title("Patching the web farm")
.Content(body => body.Panel(Ui.Panel()
.Title("Servers")
.HeaderRight("12 at once")
.Content(panelContent =>
{
panelContent.Add(lanes);
})).Add(Ui.Panel().Title("Log").Content(panelContent =>
{
panelContent.LogRegion();
}).Fill()));
foreach (string server in servers)
{
lanes.Add(server, server, steps.Length);
}
using (LiveSession session = dashboard.CreateSession())
{
await session.RunAsync(async (s, cancel) =>
{
LanesHandle handle = lanes.Handle(s);
try
{
await Parallel.ForEachAsync(
servers,
new ParallelOptions { MaxDegreeOfParallelism = 12, CancellationToken = cancel },
async (server, token) =>
{
foreach (string step in steps)
{
handle.Start(server, step);
await Task.Delay(Random.Shared.Next(40, 240), token);
handle.Advance(server, StatusKind.Pass);
}
Console.WriteLine(server + " done");
handle.Complete(server);
});
}
catch (OperationCanceledException)
{
// Ctrl+C: the session has already stopped the view; the workers just stop.
}
});
}
The recording ran the PowerShell script. This C# program does the same with the library and compiles as shown; its timings are its own.
How it works
- One thread draws. A live session starts its own render thread. It applies updates to the widgets, composes the frame and writes only the cells that changed. Your work runs on your threads and never touches the screen.
- Any thread posts. Handles (
lanes.Handle(session),table.Handle(session)),session.Postand the PowerShellUpdate-Consolecommand put an update into one lock-free first-in, first-out queue. Each thread's updates keep their order; updates from different threads have no set order relative to each other, and none is merged into a later one. The queue has no size limit, so posting does not wait for the screen; a flood that outpaces the render thread for long grows the queue in memory instead. - Updates land between frames. About 15 times a second (
LiveSessionOptions.FramesPerSecond, 1 to 60) the render thread applies the waiting updates in order, a time-boxed batch per frame (about 40 ms at 15 fps; the rest go into the next one), then draws once. Every update accepted before the session stops is applied by the end; one addressed to aWidgetIdthe view does not have is dropped and counted inEventsDropped. - Console output is captured. While a session draws on the console,
Console.OutandConsole.Errorare replaced by writers that collect whole lines from any thread (unlessCaptureConsole = false; a second capturing session fails to start).Console.Writefragments are kept per thread until that thread ends the line, so two threads writing pieces never share a line; a message that continues on another thread should go out as oneWriteLine. With a log region the lines become log entries. Without one, an inline area prints them above itself, and a full-screen view shows the latest in a short tail at the bottom (at most six rows and a third of the screen) and prints them all to the scrollback when it ends. - One write is one block. Each
Terminal.Write,Terminal.WriteLinesorTerminal.WriteMarkupLinecall is written whole, so two threads writing widgets never mix their lines. While a session owns the console, the block is queued whole and printed above an inline area, after a full-screen view ends, or in stream mode in apply order; if the session is already stopping, the caller writes the block itself, whole and once. - Stopping. When the work ends or throws, the session stops admitting updates, applies the ones already queued, draws the final frame and restores the terminal (console writers, cursor and the Windows console mode) before the exception reaches you. The first Ctrl+C does the same for the view and cancels
session.Cancellation; your work keeps running until it checks that token, and what it posts afterwards is dropped and counted inEventsDropped.HandleCancelKey = falseleaves Ctrl+C to your program. A widget callback that blocks the render thread pastStopTimeoutdelays only the final drain and screen cleanup; console capture is restored on time. A normal run ends withGetCounters()showing nothing dropped. - Not a terminal. Redirected output and CI get stream mode: each change worth a line becomes one whole line, in the order the updates were applied: every lane start and finish, status changes, table rows, finished progress and log entries, with a heartbeat summary every ten seconds. Console output is written as it arrives, in the same order, with or without a log region.
In PowerShell
The smallest case: eight runspaces at once, each writing with Write-Host. The lines go to the log panel, never over the screen:
Import-Module ConsoleMonster
$dashboard = New-ConsoleDashboard -Title 'Workers' -Content {
New-ConsolePanel -Title 'Log' -Fill -Content { New-ConsoleLogRegion }
}
1..8 | Invoke-ConsoleDashboard $dashboard -Parallel -ThrottleLimit 8 {
param($Number)
Start-Sleep -Milliseconds (Get-Random -Maximum 800)
Write-Host "worker $Number finished"
}
Invoke-ConsoleDashboard -Parallel runs a script block per input item in a runspace pool (-ThrottleLimit). Each runspace gets $ConsoleSession, so Update-Console, Write-ConsoleLogEntry and the other update commands reach the dashboard by WidgetId. Write-Host, warnings and errors from those runspaces (and verbose and debug messages when their preference is on) go to the dashboard's log (a New-ConsoleLogRegion; without one they take the same path as console output: above an -Inline area, into the short tail at the bottom of a full-screen dashboard and the scrollback after it, or as lines in stream mode); progress records go to its activity list.
Import-Module ConsoleMonster
$servers = 'web01', 'web02', 'web03', 'web04'
$dashboard = New-ConsoleDashboard -Title 'Patching' -Content {
New-ConsolePanel -Title 'Servers' -Content { $servers | New-ConsoleStatusList -WidgetId servers }
New-ConsolePanel -Title 'Log' -Fill -Content { New-ConsoleLogRegion }
}
$servers | Invoke-ConsoleDashboard $dashboard -Parallel -ThrottleLimit 4 {
param($Server)
Update-Console -WidgetId servers -Key $Server -Status Running -Detail 'patching'
Start-Sleep -Milliseconds (Get-Random -Minimum 200 -Maximum 900)
Write-Warning "$Server needs a reboot"
Update-Console -WidgetId servers -Key $Server -Status Pass -Detail 'patched'
}
- Variables of the calling script are not visible inside a runspace by themselves: read them with
$using:name(also$using:name.Memberand$using:name[index]), as withForEach-Object -Parallel, and bring helper functions in with-ImportFunction Name.-ArgumentListwith aparam()block and the input items still work. - Change widgets through the update commands, never by calling a widget object's own methods from a runspace.
Invoke-ConsoleRun -Paralleldraws its own run view: a summary bar, a cell per item and the failures. While it shows, host messages, warnings, information, verbose and debug messages and errors from the workers appear in its log, and theirWrite-Progressin an activity list; each worker's progress IDs are its own, so every worker can use-Id 0. Results keep input order (unless-Unordered), and the native stream records (warnings, errors, information, verbose and debug messages) are also delivered when the view ends, so-WarningVariableand the pipeline still get them. Its workers receive the caller's variables with$using:name. UseInvoke-ConsoleDashboard -Parallelwhen workers should update widgets of your own.
In C#
Workers update widgets through handles taken from the session. Everything below is safe from any thread while the session runs:
LanesHandle,StatusListHandle,LiveTableHandle,ProgressHandleand the other handles fromwidget.Handle(session);session.Post,session.Write(a log line) andsession.Region(name).Set(widget), which swaps aRegionWidget's content between two frames;Console.WriteLine, captured as described above;- the
ConsoleMonster.Extensions.Loggingprovider, which writes into the log region of the running session (an entry with an exception is written as ordinary output instead: above an inline area, or after a full-screen view).
The C# tab of the dashboard demo above uses Parallel.ForEachAsync with a LanesHandle. Code deeper down does not need the session at all: an ambient TerminalScope flows with the code it wraps, across await and Task.Run, and TerminalScope.Report, Advance and SetState go to the widget and key the scope names (TerminalScope.Log to the session's log). Outside a scope they do nothing, so the same code runs without a dashboard.
using ConsoleMonster.Live;
using ConsoleMonster.Widgets;
string[] servers = { "web01", "web02", "web03" };
Lanes lanes = new Lanes();
Dashboard dashboard = new Dashboard("Patching", new ConsoleMonster.Layout.Panel(lanes, "Servers"));
foreach (string server in servers) {
lanes.Add(server, server, 2);
}
using (LiveSession session = new LiveSession(dashboard)) {
session.Run(s => Parallel.ForEach(servers, server => {
// Patch knows nothing about the dashboard: the scope says where its reports go.
using (s.Scope(lanes.WidgetId, server)) {
Patch(server);
}
}));
}
static void Patch(string server) {
TerminalScope.Report("copying files");
Thread.Sleep(300);
TerminalScope.Advance();
TerminalScope.Report("restarting");
Thread.Sleep(300);
TerminalScope.Advance();
TerminalScope.SetState("pass");
}
ConsoleRun.ForEachAsync is the ready-made form: a throttle (RunOptions.ThrottleLimit), a per-item timeout the body observes through its token, failures kept per item, and the run view; see Live runs.
Under load
The stress test runs 32 workers posting updates in bursts while four more threads write to Console.Out and Console.Error at random. When it ends it fails unless every posted update was applied, nothing was dropped and the log holds exactly the stray lines that were written, then prints its counters; the recording below is that run. The benchmarks measure what one frame costs to compose and write.
Stress test · 32 workers · random Console.WriteLine · 12s 00:00:05 ╭─ Workers ─────────────────────────────────────────────────────────────────────╮ ╭─ Session ──────────────────────────╮ │ ⠴ worker 01 ━━━━━━╸───────────────────── 22% ✓ 20,568 ✗ 687 ▲ 1,585 │ │ Updates posted 730,885 │ │ ⠦ worker 02 ━━━━━━╸───────────────────── 22% ✓ 20,578 ✗ 668 ▲ 1,554 │ │ Updates applied 723,908 │ │ ⠧ worker 03 ━━━━━━╸───────────────────── 22% ✓ 20,521 ✗ 675 ▲ 1,604 │ │ Update rate 131,706/s │ │ ⠇ worker 04 ━━━━━━╸───────────────────── 22% ✓ 20,577 ✗ 701 ▲ 1,562 │ │ Frames 84 │ │ ⠏ worker 05 ━━━━━━╸───────────────────── 22% ✓ 20,542 ✗ 674 ▲ 1,624 │ │ Frame rate 15.0 fps │ │ ⠋ worker 06 ━━━━━━╸───────────────────── 23% ✓ 20,676 ✗ 675 ▲ 1,649 │ │ CPU 30% (0.3 cores) │ │ ⠙ worker 07 ━━━━━━╸───────────────────── 22% ✓ 20,402 ✗ 731 ▲ 1,627 │ │ CPU share 0.9% of 32 cores │ │ ⠹ worker 08 ━━━━━━╸───────────────────── 22% ✓ 20,638 ✗ 640 ▲ 1,562 │ │ Captured lines 96 │ │ ⠸ worker 09 ━━━━━━╸───────────────────── 22% ✓ 20,557 ✗ 642 ▲ 1,561 │ │ Dropped / errors 0 / 0 │ │ ⠼ worker 10 ━━━━━━╸───────────────────── 22% ✓ 20,501 ✗ 674 ▲ 1,585 │ │ ── updates/s ───────────────────── │ │ ⠴ worker 11 ━━━━━━╸───────────────────── 22% ✓ 20,667 ✗ 660 ▲ 1,553 │ │ ▅▄▆▅▄█▇█▇█▆ │ │ ⠦ worker 12 ━━━━━━╸───────────────────── 22% ✓ 20,539 ✗ 665 ▲ 1,636 │ │ ███████████ │ │ ⠧ worker 13 ━━━━━━╸───────────────────── 22% ✓ 20,475 ✗ 707 ▲ 1,658 │ │ ███████████ 132k/s │ │ ⠇ worker 14 ━━━━━━╸───────────────────── 22% ✓ 20,650 ✗ 693 ▲ 1,577 │ │ ── CPU % (100% = one core) ─────── │ │ ⠏ worker 15 ━━━━━━╸───────────────────── 22% ✓ 20,577 ✗ 693 ▲ 1,570 │ │ 72.9%│⠒⠒⠒⠒⠊⠉⠢⡀ │ │ ⠋ worker 16 ━━━━━━╸───────────────────── 22% ✓ 20,601 ✗ 696 ▲ 1,663 │ │ │ ⠑⢄ ⢀⢄ ⢀⣀⡀ │ │ ⠙ worker 17 ━━━━━━╸───────────────────── 23% ✓ 20,722 ✗ 727 ▲ 1,591 │ │ │ ⠑⢄⢀⠔⠁ ⠉⠢⢄⡀⢀⡠⠒⠉⠁ ⠈⠒⢄ │ │ ⠹ worker 18 ━━━━━━╸───────────────────── 22% ✓ 20,575 ✗ 745 ▲ 1,640 │ │ │ ⠁ ⠈⠁ │ │ ⠸ worker 19 ━━━━━━╸───────────────────── 22% ✓ 20,547 ✗ 680 ▲ 1,613 │ │ 0%│ │ │ ⠼ worker 20 ━━━━━━╸───────────────────── 22% ✓ 20,670 ✗ 649 ▲ 1,641 │ │ └──────────────────────────── │ │ ⠴ worker 21 ━━━━━━╸───────────────────── 22% ✓ 20,695 ✗ 689 ▲ 1,496 │ │ │ │ ⠦ worker 22 ━━━━━━╸───────────────────── 22% ✓ 20,619 ✗ 663 ▲ 1,598 │ │ │ │ ⠧ worker 23 ━━━━━━╸───────────────────── 22% ✓ 20,652 ✗ 697 ▲ 1,611 │ │ │ │ ⠇ worker 24 ━━━━━━╸───────────────────── 22% ✓ 20,590 ✗ 670 ▲ 1,620 │ │ │ │ ⠏ worker 25 ━━━━━━╸───────────────────── 22% ✓ 20,756 ✗ 681 ▲ 1,523 │ │ │ │ ⠋ worker 26 ━━━━━━╸───────────────────── 22% ✓ 20,529 ✗ 703 ▲ 1,568 │ │ │ │ ⠙ worker 27 ━━━━━━╸───────────────────── 23% ✓ 20,697 ✗ 733 ▲ 1,570 │ │ │ │ ⠹ worker 28 ━━━━━━╸───────────────────── 22% ✓ 20,377 ✗ 673 ▲ 1,630 │ │ │ │ ⠸ worker 29 ━━━━━━╸───────────────────── 22% ✓ 20,563 ✗ 769 ▲ 1,548 │ │ │ │ ⠼ worker 30 ━━━━━━╸───────────────────── 23% ✓ 20,767 ✗ 687 ▲ 1,586 │ │ │ │ ⠴ worker 31 ━━━━━━╸───────────────────── 22% ✓ 20,561 ✗ 718 ▲ 1,521 │ │ │ │ ⠦ worker 32 ━━━━━━╸───────────────────── 22% ✓ 20,530 ✗ 736 ▲ 1,574 │ │ │ ╰───────────────────────────────────────────────────────────────────────────────╯ ╰────────────────────────────────────╯ ╭─ Captured output ────────────────────────────────────────────────────────────────────────────────────────────────────╮ │ 00:05 ✗ ERR ERROR FakeLib: GC pause 119 ms │ ╰──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────╯ ctrl+c stop
- Updates posted in 12.9 s
- 1,584,629
- Average update rate
- 123,020/s
- Frames drawn
- 194 (15.1 fps)
- Dropped updates and errors
- 0 / 0
- CPU, share of one core
- 38.6%
STRESS seconds=12.9 workers=32 posted=1584629 avgRate=123020/s peakRate=140585/s frames=194 fps=15.1 cpuOneCore=38.6% cpuMachine=1.2% captured=209 dropped=0 errors=0 runtime=.NET 8.0.34// A stress test: 32 workers post thousands of updates a second while a noisy "library" writes to Console.Out and
// Console.Error from four threads. Workers never touch the console; the session draws about 15 frames a second and
// captures the stray lines into the output panel. Run it for N seconds: dotnet run -- 12
int seconds = args.Length > 0 ? int.Parse(args[0], CultureInfo.InvariantCulture) : 12;
const int Workers = 32;
Lanes lanes = new Lanes("workers")
{
MaxLabelWidth = 10,
ShowDetail = true
};
for (int i = 0; i < Workers; i++)
{
lanes.Add("w" + i, "worker " + (i + 1).ToString("00", CultureInfo.InvariantCulture), 100000);
}
KeyValueList stats = new KeyValueList("stats")
.Add("Updates posted", "0")
.Add("Updates applied", "0")
.Add("Update rate", "-")
.Add("Frames", "0")
.Add("Frame rate", "-")
.Add("CPU", "-")
.Add("CPU share", "-")
.Add("Captured lines", "0")
.Add("Dropped / errors", "0 / 0");
Sparkline rate = new Sparkline("rate").Height(3).Unit("/s");
LineChart cpu = new LineChart("cpu").Height(6).Minimum(0).Unit("%");
cpu.Series("cpu", ThemeToken.Accent2);
Dashboard dashboard = Ui.Dashboard().Title("[bold]Stress test[/]")
.Subtitle(Workers + " workers · random Console.WriteLine · " + seconds + "s")
.Content(body => body
.Columns(columns => columns.Content(c => c.Add(new Panel(lanes, "Workers").Fill(2.2))
.Add(new Panel(new Rows(
stats,
new Rule("updates/s"),
rate,
new Rule("CPU % (100% = one core)"),
cpu), "Session").Fill(1))))
.Add(new Panel(new LogRegion { PreferredHeight = 6 }, "Captured output").Fill()));
string result = string.Empty;
using (LiveSession session = new LiveSession(dashboard))
{
session.Run(s => result = Drive(s));
}
Console.WriteLine(result);
string Drive(LiveSession session)
// … 151 more lines in the full programFull program
using ConsoleMonster;
using System.Diagnostics;
using System.Globalization;
using ConsoleMonster.Layout;
using ConsoleMonster.Live;
using ConsoleMonster.Styling;
using ConsoleMonster.Widgets;
// A stress test: 32 workers post thousands of updates a second while a noisy "library" writes to Console.Out and
// Console.Error from four threads. Workers never touch the console; the session draws about 15 frames a second and
// captures the stray lines into the output panel. Run it for N seconds: dotnet run -- 12
int seconds = args.Length > 0 ? int.Parse(args[0], CultureInfo.InvariantCulture) : 12;
const int Workers = 32;
Lanes lanes = new Lanes("workers")
{
MaxLabelWidth = 10,
ShowDetail = true
};
for (int i = 0; i < Workers; i++)
{
lanes.Add("w" + i, "worker " + (i + 1).ToString("00", CultureInfo.InvariantCulture), 100000);
}
KeyValueList stats = new KeyValueList("stats")
.Add("Updates posted", "0")
.Add("Updates applied", "0")
.Add("Update rate", "-")
.Add("Frames", "0")
.Add("Frame rate", "-")
.Add("CPU", "-")
.Add("CPU share", "-")
.Add("Captured lines", "0")
.Add("Dropped / errors", "0 / 0");
Sparkline rate = new Sparkline("rate").Height(3).Unit("/s");
LineChart cpu = new LineChart("cpu").Height(6).Minimum(0).Unit("%");
cpu.Series("cpu", ThemeToken.Accent2);
Dashboard dashboard = Ui.Dashboard().Title("[bold]Stress test[/]")
.Subtitle(Workers + " workers · random Console.WriteLine · " + seconds + "s")
.Content(body => body
.Columns(columns => columns.Content(c => c.Add(new Panel(lanes, "Workers").Fill(2.2))
.Add(new Panel(new Rows(
stats,
new Rule("updates/s"),
rate,
new Rule("CPU % (100% = one core)"),
cpu), "Session").Fill(1))))
.Add(new Panel(new LogRegion { PreferredHeight = 6 }, "Captured output").Fill()));
string result = string.Empty;
using (LiveSession session = new LiveSession(dashboard))
{
session.Run(s => result = Drive(s));
}
Console.WriteLine(result);
string Drive(LiveSession session)
{
LanesHandle lanesHandle = lanes.Handle(session);
KeyValueHandle statsHandle = stats.Handle(session);
SparklineHandle rateHandle = rate.Handle(session);
SparklineHandle cpuHandle = cpu.Handle(session);
long captured = 0;
using CancellationTokenSource stop = CancellationTokenSource.CreateLinkedTokenSource(
session.Cancellation);
Thread[] workers = new Thread[Workers];
for (int i = 0; i < Workers; i++)
{
int id = i;
workers[i] = new Thread(() => Worker(id, lanesHandle, stop.Token))
{
IsBackground = true
};
workers[i].Start();
}
Thread[] noisy = new Thread[4];
for (int i = 0; i < noisy.Length; i++)
{
int id = i;
noisy[i] = new Thread(() => FakeLibrary(id, stop.Token, ref captured))
{
IsBackground = true
};
noisy[i].Start();
}
Process process = Process.GetCurrentProcess();
Stopwatch wall = Stopwatch.StartNew();
TimeSpan cpuStart = process.TotalProcessorTime;
TimeSpan lastCpu = cpuStart;
double lastWall = 0;
long lastPosted = 0;
double peakRate = 0;
while (wall.Elapsed.TotalSeconds < seconds && !session.Cancellation.IsCancellationRequested)
{
Thread.Sleep(500);
process.Refresh();
double now = wall.Elapsed.TotalSeconds;
TimeSpan cpuNow = process.TotalProcessorTime;
double interval = now - lastWall;
double core = (cpuNow - lastCpu).TotalMilliseconds / (interval * 1000) * 100;
long posted = session.EventsPosted;
double perSecond = (posted - lastPosted) / interval;
peakRate = Math.Max(peakRate, perSecond);
lastCpu = cpuNow;
lastWall = now;
lastPosted = posted;
rateHandle.Add(perSecond);
cpuHandle.Add(core, "cpu");
statsHandle.Set("Updates posted", NumberFormat.Grouped(posted));
statsHandle.Set("Updates applied", NumberFormat.Grouped(session.EventsApplied));
statsHandle.Set("Update rate", NumberFormat.Grouped(perSecond) + "/s");
statsHandle.Set("Frames", NumberFormat.Grouped(session.FramesRendered));
statsHandle.Set("Frame rate",
(session.FramesRendered / now).ToString("0.0", CultureInfo.InvariantCulture) + " fps");
statsHandle.Set("CPU",
core.ToString("0",
CultureInfo.InvariantCulture) + "% (" + (core / 100).ToString("0.0",
CultureInfo.InvariantCulture) + " cores)");
statsHandle.Set("CPU share",
(core / Environment.ProcessorCount).ToString("0.0",
CultureInfo.InvariantCulture) + "% of " + Environment.ProcessorCount + " cores");
statsHandle.Set("Captured lines", NumberFormat.Grouped(Interlocked.Read(ref captured)));
statsHandle.Set("Dropped / errors", session.EventsDropped + " / " + session.ApplyErrors);
}
stop.Cancel();
foreach (Thread t in workers)
{
t.Join();
}
foreach (Thread t in noisy)
{
t.Join();
}
for (int i = 0; i < Workers; i++)
{
lanesHandle.Complete("w" + i, StatusKind.Pass);
}
Thread.Sleep(300);
process.Refresh();
double elapsed = wall.Elapsed.TotalSeconds;
double avgCore = (process.TotalProcessorTime - cpuStart).TotalMilliseconds
/ (elapsed * 1000) * 100;
return string.Format(CultureInfo.InvariantCulture,
("STRESS seconds={0:0.0} workers={1} posted={2} avgRate={3:0}/s "
+ "peakRate={4:0}/s frames={5} fps={6:0.0} cpuOneCore={7:0.0}% "
+ "cpuMachine={8:0.0}% captured={9} dropped={10} errors={11} runtime={12}"),
elapsed, Workers, session.EventsPosted, session.EventsPosted / elapsed, peakRate,
session.FramesRendered, session.FramesRendered / elapsed, avgCore,
avgCore / Environment.ProcessorCount, Interlocked.Read(ref captured), session.EventsDropped,
session.ApplyErrors,
System.Runtime.InteropServices.RuntimeInformation.FrameworkDescription);
}
void Worker(int id, LanesHandle handle, CancellationToken token)
{
string key = "w" + id;
Random random = new Random(id * 7919);
string[] steps = { "parsing", "resolving", "evaluating", "scoring", "writing" };
handle.Start(key, "starting");
int n = 0;
while (!token.IsCancellationRequested)
{
for (int burst = 0; burst < 40; burst++)
{
double roll = random.NextDouble();
StatusKind outcome = roll < 0.03
? StatusKind.Fail
: roll < 0.1 ? StatusKind.Warn : StatusKind.Pass;
handle.Advance(key, outcome,
(n++ % 97 == 0) ? steps[random.Next(steps.Length)] + " item " + n : null);
}
Thread.Sleep(1);
}
}
void FakeLibrary(int id, CancellationToken token, ref long captured)
{
Random random = new Random(1000 + id);
string[] messages =
{
"FakeLib: cache miss for key {0}", "FakeLib: retrying request {0} (attempt 2)",
"FakeLib: connection pool at {0}% capacity", "FakeLib: GC pause {0} ms",
"FakeLib: flushed {0} records"
};
while (!token.IsCancellationRequested)
{
Thread.Sleep(random.Next(40, 400));
string text = string.Format(CultureInfo.InvariantCulture,
messages[random.Next(messages.Length)], random.Next(1, 999));
if (random.NextDouble() < 0.15)
{
Console.Error.WriteLine("ERROR " + text);
}
else
{
Console.WriteLine(text);
}
Interlocked.Increment(ref captured);
}
}// A stress test: 32 workers post thousands of updates a second while a noisy "library" writes to Console.Out and
// Console.Error from four threads. Workers never touch the console; the session draws about 15 frames a second and
// captures the stray lines into the output panel. Run it for N seconds: dotnet run -- 12
int seconds = args.Length > 0 ? int.Parse(args[0], CultureInfo.InvariantCulture) : 12;
const int Workers = 32;
Lanes lanes = Ui.Lanes("workers").MaxLabelWidth(10).ShowDetail();
for (int i = 0; i < Workers; i++)
{
lanes.Add("w" + i, "worker " + (i + 1).ToString("00", CultureInfo.InvariantCulture), 100000);
}
KeyValueList stats = Ui.KeyValue("stats")
.Add("Updates posted", "0")
.Add("Updates applied", "0")
.Add("Update rate", "-")
.Add("Frames", "0")
.Add("Frame rate", "-")
.Add("CPU", "-")
.Add("CPU share", "-")
.Add("Captured lines", "0")
.Add("Dropped / errors", "0 / 0");
Sparkline rate = Ui.Sparkline("rate").Height(3).Unit("/s");
LineChart cpu = Ui.LineChart("cpu").Height(6).Minimum(0).Unit("%");
cpu.Series("cpu", ThemeToken.Accent2);
Dashboard dashboard = Ui.Dashboard()
.Title("[bold]Stress test[/]")
.Subtitle(Workers + " workers · random Console.WriteLine · " + seconds + "s")
.Content(body => body.Columns(columns => columns.Content(c => c.Add(Ui.Panel()
.Title("Workers")
.Content(panelContent =>
{
panelContent.Add(lanes);
})
.Fill(2.2)).Add(Ui.Panel().Title("Session").Content(panelContent =>
{
panelContent.Rows(r => r.Content(rowsContent =>
{
rowsContent.Add(stats);
rowsContent.Rule("updates/s");
rowsContent.Add(rate);
rowsContent.Rule("CPU % (100% = one core)");
rowsContent.Add(cpu);
}));
}).Fill(1)))).Add(Ui.Panel().Title("Captured output").Content(panelContent =>
{
panelContent.LogRegion(logRegion => logRegion.PreferredHeight(6));
}).Fill()));
string result = string.Empty;
using (LiveSession session = dashboard.CreateSession())
{
session.Run(s => result = Drive(s));
}
Console.WriteLine(result);
string Drive(LiveSession session)
{
LanesHandle lanesHandle = lanes.Handle(session);
KeyValueHandle statsHandle = stats.Handle(session);
SparklineHandle rateHandle = rate.Handle(session);
SparklineHandle cpuHandle = cpu.Handle(session);
long captured = 0;
using CancellationTokenSource stop = CancellationTokenSource.CreateLinkedTokenSource(
session.Cancellation);
Thread[] workers = new Thread[Workers];
for (int i = 0; i < Workers; i++)
{
int id = i;
workers[i] = new Thread(() => Worker(id, lanesHandle, stop.Token))
{
IsBackground = true
};
workers[i].Start();
}
Thread[] noisy = new Thread[4];
for (int i = 0; i < noisy.Length; i++)
{
int id = i;
noisy[i] = new Thread(() => FakeLibrary(id, stop.Token, ref captured))
{
IsBackground = true
};
noisy[i].Start();
}
Process process = Process.GetCurrentProcess();
Stopwatch wall = Stopwatch.StartNew();
TimeSpan cpuStart = process.TotalProcessorTime;
TimeSpan lastCpu = cpuStart;
double lastWall = 0;
long lastPosted = 0;
double peakRate = 0;
while (wall.Elapsed.TotalSeconds < seconds && !session.Cancellation.IsCancellationRequested)
{
Thread.Sleep(500);
process.Refresh();
double now = wall.Elapsed.TotalSeconds;
TimeSpan cpuNow = process.TotalProcessorTime;
double interval = now - lastWall;
double core = (cpuNow - lastCpu).TotalMilliseconds / (interval * 1000) * 100;
long posted = session.EventsPosted;
double perSecond = (posted - lastPosted) / interval;
peakRate = Math.Max(peakRate, perSecond);
lastCpu = cpuNow;
lastWall = now;
lastPosted = posted;
rateHandle.Add(perSecond);
cpuHandle.Add(core, "cpu");
statsHandle.Set("Updates posted", NumberFormat.Grouped(posted));
statsHandle.Set("Updates applied", NumberFormat.Grouped(session.EventsApplied));
statsHandle.Set("Update rate", NumberFormat.Grouped(perSecond) + "/s");
statsHandle.Set("Frames", NumberFormat.Grouped(session.FramesRendered));
statsHandle.Set("Frame rate",
(session.FramesRendered / now).ToString("0.0", CultureInfo.InvariantCulture) + " fps");
statsHandle.Set("CPU",
core.ToString("0",
CultureInfo.InvariantCulture) + "% (" + (core / 100).ToString("0.0",
CultureInfo.InvariantCulture) + " cores)");
statsHandle.Set("CPU share",
(core / Environment.ProcessorCount).ToString("0.0",
CultureInfo.InvariantCulture) + "% of " + Environment.ProcessorCount + " cores");
statsHandle.Set("Captured lines", NumberFormat.Grouped(Interlocked.Read(ref captured)));
statsHandle.Set("Dropped / errors", session.EventsDropped + " / " + session.ApplyErrors);
}
stop.Cancel();
foreach (Thread t in workers)
{
t.Join();
}
foreach (Thread t in noisy)
{
t.Join();
}
for (int i = 0; i < Workers; i++)
{
lanesHandle.Complete("w" + i, StatusKind.Pass);
}
Thread.Sleep(300);
process.Refresh();
double elapsed = wall.Elapsed.TotalSeconds;
double avgCore = (process.TotalProcessorTime - cpuStart).TotalMilliseconds / (elapsed * 1000) * 100;
return string.Format(CultureInfo.InvariantCulture,
("STRESS seconds={0:0.0} workers={1} posted={2} avgRate={3:0}/s "
+ "peakRate={4:0}/s frames={5} fps={6:0.0} cpuOneCore={7:0.0}% "
+ "cpuMachine={8:0.0}% captured={9} dropped={10} errors={11} runtime={12}"),
elapsed, Workers, session.EventsPosted, session.EventsPosted / elapsed, peakRate,
session.FramesRendered, session.FramesRendered / elapsed, avgCore,
avgCore / Environment.ProcessorCount, Interlocked.Read(ref captured), session.EventsDropped,
session.ApplyErrors,
System.Runtime.InteropServices.RuntimeInformation.FrameworkDescription);
}
void Worker(int id, LanesHandle handle, CancellationToken token)
{
string key = "w" + id;
Random random = new Random(id * 7919);
string[] steps = { "parsing", "resolving", "evaluating", "scoring", "writing" };
handle.Start(key, "starting");
int n = 0;
while (!token.IsCancellationRequested)
{
for (int burst = 0; burst < 40; burst++)
{
double roll = random.NextDouble();
StatusKind outcome = roll < 0.03
? StatusKind.Fail
: roll < 0.1 ? StatusKind.Warn : StatusKind.Pass;
handle.Advance(key, outcome,
(n++ % 97 == 0) ? steps[random.Next(steps.Length)] + " item " + n : null);
}
Thread.Sleep(1);
}
}
void FakeLibrary(int id, CancellationToken token, ref long captured)
{
Random random = new Random(1000 + id);
string[] messages =
{
"FakeLib: cache miss for key {0}", "FakeLib: retrying request {0} (attempt 2)",
"FakeLib: connection pool at {0}% capacity", "FakeLib: GC pause {0} ms",
"FakeLib: flushed {0} records"
};
while (!token.IsCancellationRequested)
{
Thread.Sleep(random.Next(40, 400));
string text = string.Format(CultureInfo.InvariantCulture,
messages[random.Next(messages.Length)], random.Next(1, 999));
if (random.NextDouble() < 0.15)
{
Console.Error.WriteLine("ERROR " + text);
}
else
{
Console.WriteLine(text);
}
Interlocked.Increment(ref captured);
}
}
Full program
using ConsoleMonster;
using System.Diagnostics;
using System.Globalization;
using ConsoleMonster.Layout;
using ConsoleMonster.Live;
using ConsoleMonster.Styling;
using ConsoleMonster.Widgets;
// A stress test: 32 workers post thousands of updates a second while a noisy "library" writes to Console.Out and
// Console.Error from four threads. Workers never touch the console; the session draws about 15 frames a second and
// captures the stray lines into the output panel. Run it for N seconds: dotnet run -- 12
int seconds = args.Length > 0 ? int.Parse(args[0], CultureInfo.InvariantCulture) : 12;
const int Workers = 32;
Lanes lanes = Ui.Lanes("workers").MaxLabelWidth(10).ShowDetail();
for (int i = 0; i < Workers; i++)
{
lanes.Add("w" + i, "worker " + (i + 1).ToString("00", CultureInfo.InvariantCulture), 100000);
}
KeyValueList stats = Ui.KeyValue("stats")
.Add("Updates posted", "0")
.Add("Updates applied", "0")
.Add("Update rate", "-")
.Add("Frames", "0")
.Add("Frame rate", "-")
.Add("CPU", "-")
.Add("CPU share", "-")
.Add("Captured lines", "0")
.Add("Dropped / errors", "0 / 0");
Sparkline rate = Ui.Sparkline("rate").Height(3).Unit("/s");
LineChart cpu = Ui.LineChart("cpu").Height(6).Minimum(0).Unit("%");
cpu.Series("cpu", ThemeToken.Accent2);
Dashboard dashboard = Ui.Dashboard()
.Title("[bold]Stress test[/]")
.Subtitle(Workers + " workers · random Console.WriteLine · " + seconds + "s")
.Content(body => body.Columns(columns => columns.Content(c => c.Add(Ui.Panel()
.Title("Workers")
.Content(panelContent =>
{
panelContent.Add(lanes);
})
.Fill(2.2)).Add(Ui.Panel().Title("Session").Content(panelContent =>
{
panelContent.Rows(r => r.Content(rowsContent =>
{
rowsContent.Add(stats);
rowsContent.Rule("updates/s");
rowsContent.Add(rate);
rowsContent.Rule("CPU % (100% = one core)");
rowsContent.Add(cpu);
}));
}).Fill(1)))).Add(Ui.Panel().Title("Captured output").Content(panelContent =>
{
panelContent.LogRegion(logRegion => logRegion.PreferredHeight(6));
}).Fill()));
string result = string.Empty;
using (LiveSession session = dashboard.CreateSession())
{
session.Run(s => result = Drive(s));
}
Console.WriteLine(result);
string Drive(LiveSession session)
{
LanesHandle lanesHandle = lanes.Handle(session);
KeyValueHandle statsHandle = stats.Handle(session);
SparklineHandle rateHandle = rate.Handle(session);
SparklineHandle cpuHandle = cpu.Handle(session);
long captured = 0;
using CancellationTokenSource stop = CancellationTokenSource.CreateLinkedTokenSource(
session.Cancellation);
Thread[] workers = new Thread[Workers];
for (int i = 0; i < Workers; i++)
{
int id = i;
workers[i] = new Thread(() => Worker(id, lanesHandle, stop.Token))
{
IsBackground = true
};
workers[i].Start();
}
Thread[] noisy = new Thread[4];
for (int i = 0; i < noisy.Length; i++)
{
int id = i;
noisy[i] = new Thread(() => FakeLibrary(id, stop.Token, ref captured))
{
IsBackground = true
};
noisy[i].Start();
}
Process process = Process.GetCurrentProcess();
Stopwatch wall = Stopwatch.StartNew();
TimeSpan cpuStart = process.TotalProcessorTime;
TimeSpan lastCpu = cpuStart;
double lastWall = 0;
long lastPosted = 0;
double peakRate = 0;
while (wall.Elapsed.TotalSeconds < seconds && !session.Cancellation.IsCancellationRequested)
{
Thread.Sleep(500);
process.Refresh();
double now = wall.Elapsed.TotalSeconds;
TimeSpan cpuNow = process.TotalProcessorTime;
double interval = now - lastWall;
double core = (cpuNow - lastCpu).TotalMilliseconds / (interval * 1000) * 100;
long posted = session.EventsPosted;
double perSecond = (posted - lastPosted) / interval;
peakRate = Math.Max(peakRate, perSecond);
lastCpu = cpuNow;
lastWall = now;
lastPosted = posted;
rateHandle.Add(perSecond);
cpuHandle.Add(core, "cpu");
statsHandle.Set("Updates posted", NumberFormat.Grouped(posted));
statsHandle.Set("Updates applied", NumberFormat.Grouped(session.EventsApplied));
statsHandle.Set("Update rate", NumberFormat.Grouped(perSecond) + "/s");
statsHandle.Set("Frames", NumberFormat.Grouped(session.FramesRendered));
statsHandle.Set("Frame rate",
(session.FramesRendered / now).ToString("0.0", CultureInfo.InvariantCulture) + " fps");
statsHandle.Set("CPU",
core.ToString("0",
CultureInfo.InvariantCulture) + "% (" + (core / 100).ToString("0.0",
CultureInfo.InvariantCulture) + " cores)");
statsHandle.Set("CPU share",
(core / Environment.ProcessorCount).ToString("0.0",
CultureInfo.InvariantCulture) + "% of " + Environment.ProcessorCount + " cores");
statsHandle.Set("Captured lines", NumberFormat.Grouped(Interlocked.Read(ref captured)));
statsHandle.Set("Dropped / errors", session.EventsDropped + " / " + session.ApplyErrors);
}
stop.Cancel();
foreach (Thread t in workers)
{
t.Join();
}
foreach (Thread t in noisy)
{
t.Join();
}
for (int i = 0; i < Workers; i++)
{
lanesHandle.Complete("w" + i, StatusKind.Pass);
}
Thread.Sleep(300);
process.Refresh();
double elapsed = wall.Elapsed.TotalSeconds;
double avgCore = (process.TotalProcessorTime - cpuStart).TotalMilliseconds / (elapsed * 1000) * 100;
return string.Format(CultureInfo.InvariantCulture,
("STRESS seconds={0:0.0} workers={1} posted={2} avgRate={3:0}/s "
+ "peakRate={4:0}/s frames={5} fps={6:0.0} cpuOneCore={7:0.0}% "
+ "cpuMachine={8:0.0}% captured={9} dropped={10} errors={11} runtime={12}"),
elapsed, Workers, session.EventsPosted, session.EventsPosted / elapsed, peakRate,
session.FramesRendered, session.FramesRendered / elapsed, avgCore,
avgCore / Environment.ProcessorCount, Interlocked.Read(ref captured), session.EventsDropped,
session.ApplyErrors,
System.Runtime.InteropServices.RuntimeInformation.FrameworkDescription);
}
void Worker(int id, LanesHandle handle, CancellationToken token)
{
string key = "w" + id;
Random random = new Random(id * 7919);
string[] steps = { "parsing", "resolving", "evaluating", "scoring", "writing" };
handle.Start(key, "starting");
int n = 0;
while (!token.IsCancellationRequested)
{
for (int burst = 0; burst < 40; burst++)
{
double roll = random.NextDouble();
StatusKind outcome = roll < 0.03
? StatusKind.Fail
: roll < 0.1 ? StatusKind.Warn : StatusKind.Pass;
handle.Advance(key, outcome,
(n++ % 97 == 0) ? steps[random.Next(steps.Length)] + " item " + n : null);
}
Thread.Sleep(1);
}
}
void FakeLibrary(int id, CancellationToken token, ref long captured)
{
Random random = new Random(1000 + id);
string[] messages =
{
"FakeLib: cache miss for key {0}", "FakeLib: retrying request {0} (attempt 2)",
"FakeLib: connection pool at {0}% capacity", "FakeLib: GC pause {0} ms",
"FakeLib: flushed {0} records"
};
while (!token.IsCancellationRequested)
{
Thread.Sleep(random.Next(40, 400));
string text = string.Format(CultureInfo.InvariantCulture,
messages[random.Next(messages.Length)], random.Next(1, 999));
if (random.NextDouble() < 0.15)
{
Console.Error.WriteLine("ERROR " + text);
}
else
{
Console.WriteLine(text);
}
Interlocked.Increment(ref captured);
}
}
What is and is not thread-safe
| Safe from any thread while a session runs | Not safe from several threads |
|---|---|
Handles from widget.Handle(session), session.Post, session.Write, session.Region(name).Set | Calling a widget object's own methods (table.Set, lanes.Add, log.Write) while the session or another thread uses it |
Console.WriteLine, Console.Error.WriteLine and Console.Write fragments (kept per thread until the line ends) | One message split across several threads (send it as one WriteLine) |
Terminal.Write, Terminal.WriteLines and Terminal.WriteMarkupLine (each call one whole block) | Drawing your own InlineArea from several threads |
TerminalScope reports in any task or thread that inherited the scope | |
The Update-Console command in Invoke-ConsoleDashboard -Parallel runspaces | Widget objects changed from a runspace instead of through the update commands |
Build a widget fully before the session starts, then change it only through handles or update commands while it runs. A handle used after the session stopped is harmless: the update is dropped and counted in EventsDropped.
Guarantees
- Whole lines and blocks. While a session runs, many threads writing at once never split a line, and the lines of one
Terminal.Writenever mix with another's. - Order per producer. Each thread's updates arrive in the order it sent them.
- Posting never waits for the screen. Workers keep going while drawing catches up, and every accepted update is handled exactly once (applied, or counted in
EventsDroppedwhen itsWidgetIddoes not exist). - No drops under load. A normal run ends with every posted update applied and nothing dropped, even with dozens of workers and stray console output.
- Clean shutdown. When the work ends or throws, queued updates and output are written exactly once and the terminal is restored (see Stopping for a widget callback that blocks drawing).
- Ctrl+C. The first Ctrl+C stops new updates and restores the terminal and the console writers.
- PowerShell workers. Host messages, warnings and progress from
Invoke-ConsoleDashboard -ParallelandInvoke-ConsoleRun -Parallelreach the view without changing what the script returns. - CI and redirected output. Whole lines, in the order the updates were applied.
Each guarantee is covered by automated tests on .NET Framework 4.7.2, .NET 8, .NET 10 and PowerShell 5.1 and 7 (running the tests).
What a frame costs is on the benchmarks page.
Next
- Live log tails: follow a file or event log in a live view.
- Dashboard frames: a printed summary with facts, meters and attention items.
- Live runs: parallel work with a ready-made view.