Skip to content
ConsoleMonster

Threads and concurrency

Any thread can update a live view: updates go through one queue, one thread draws, console output is captured, and CI gets whole, ordered lines.

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.

ForEach-Object -Parallel 100×2424-bitFull
Install-Module ConsoleMonster -Scope CurrentUser
PowerShellthreads-naive.ps1View on GitHub
# 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

Terminal
dotnet new console -n Threads
cd Threads
dotnet add package ConsoleMonster
C#Program.csView on GitHub
// 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.

Terminal
dotnet new console -n Threads
cd Threads
dotnet add package ConsoleMonster
C# fluentProgram.cs
// 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.

Invoke-ConsoleDashboard -Parallel 100×2224-bitFull
Install-Module ConsoleMonster -Scope CurrentUser
PowerShellthreads-dashboard.ps1View on GitHub
# 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

Terminal
dotnet new console -n ThreadsDashboard
cd ThreadsDashboard
dotnet add package ConsoleMonster
C#Program.csView on GitHub
// 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.

Terminal
dotnet new console -n ThreadsDashboard
cd ThreadsDashboard
dotnet add package ConsoleMonster
C# fluentProgram.cs
// 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.

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.

CI=true 100×3024-bitFull
Install-Module ConsoleMonster -Scope CurrentUser
PowerShellthreads-dashboard.ps1View on GitHub
# 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

C#Program.csView on GitHub
// 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.

C# fluentProgram.cs
// 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 queue, one thread that drawsWorker threads and runspaces post updates into one first-in first-out queue. The render thread applies them between frames, about 15 times a second, and draws the console. Console.WriteLine calls are captured as whole lines and become log updates.worker threadworker threadrunspaceupdate queue (FIFO)render threadConsole.WriteLinecaptured linepost from any threadapplies, then drawsabout 15 frames a seconda log entry
  • 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.Post and the PowerShell Update-Console command 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 a WidgetId the view does not have is dropped and counted in EventsDropped.
  • Console output is captured. While a session draws on the console, Console.Out and Console.Error are replaced by writers that collect whole lines from any thread (unless CaptureConsole = false; a second capturing session fails to start). Console.Write fragments 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 one WriteLine. 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.WriteLines or Terminal.WriteMarkupLine call 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 in EventsDropped. HandleCancelKey = false leaves Ctrl+C to your program. A widget callback that blocks the render thread past StopTimeout delays only the final drain and screen cleanup; console capture is restored on time. A normal run ends with GetCounters() 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.Member and $using:name[index]), as with ForEach-Object -Parallel, and bring helper functions in with -ImportFunction Name. -ArgumentList with a param() 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 -Parallel draws 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 their Write-Progress in 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 -WarningVariable and the pipeline still get them. Its workers receive the caller's variables with $using:name. Use Invoke-ConsoleDashboard -Parallel when 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, ProgressHandle and the other handles from widget.Handle(session);
  • session.Post, session.Write (a log line) and session.Region(name).Set(widget), which swaps a RegionWidget's content between two frames;
  • Console.WriteLine, captured as described above;
  • the ConsoleMonster.Extensions.Logging provider, 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.

dotnet run -- 12 120×4024-bitFull
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%
Result line
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
C#Program.cs
// 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 program
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 = 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);
    }
}
C# fluentProgram.cs
// 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);
    }
}
The stress test: 32 workers and stray console writes, recorded from the program below it.

What is and is not thread-safe

Safe from any thread while a session runsNot safe from several threads
Handles from widget.Handle(session), session.Post, session.Write, session.Region(name).SetCalling 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 runspacesWidget 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.Write never 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 EventsDropped when its WidgetId does 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 -Parallel and Invoke-ConsoleRun -Parallel reach 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

Edit this page on GitHub