AdaskoTheBeAsT.Interop.Execution.Hosting 3.0.0

There is a newer version of this package available.
See the version list below for details.
dotnet add package AdaskoTheBeAsT.Interop.Execution.Hosting --version 3.0.0
                    
NuGet\Install-Package AdaskoTheBeAsT.Interop.Execution.Hosting -Version 3.0.0
                    
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="AdaskoTheBeAsT.Interop.Execution.Hosting" Version="3.0.0" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="AdaskoTheBeAsT.Interop.Execution.Hosting" Version="3.0.0" />
                    
Directory.Packages.props
<PackageReference Include="AdaskoTheBeAsT.Interop.Execution.Hosting" />
                    
Project file
For projects that support Central Package Management (CPM), copy this XML node into the solution Directory.Packages.props file to version the package.
paket add AdaskoTheBeAsT.Interop.Execution.Hosting --version 3.0.0
                    
#r "nuget: AdaskoTheBeAsT.Interop.Execution.Hosting, 3.0.0"
                    
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
#:package AdaskoTheBeAsT.Interop.Execution.Hosting@3.0.0
                    
#:package directive can be used in C# file-based apps starting in .NET 10 preview 4. Copy this into a .cs file before any lines of code to reference the package.
#addin nuget:?package=AdaskoTheBeAsT.Interop.Execution.Hosting&version=3.0.0
                    
Install as a Cake Addin
#tool nuget:?package=AdaskoTheBeAsT.Interop.Execution.Hosting&version=3.0.0
                    
Install as a Cake Tool

AdaskoTheBeAsT.Interop

A focused interop toolbox for dedicated-thread execution, native library isolation, and COM-friendly workloads.

NuGet NuGet NuGet NuGet License: MIT TFMs Warnings Deterministic

πŸ”¬ Code quality β€” SonarCloud

Quality Gate Status Coverage Maintainability Rating Reliability Rating Security Rating Bugs Vulnerabilities Code Smells Duplicated Lines (%) Technical Debt Lines of Code


πŸ‘‹ Hello, interop friend

Interop code is fun, right up until it isn't. You know the signs:

  • 🧬 a native library that secretly wants thread affinity
  • 🏒 a COM component that quietly insists on STA + message pumping
  • 🧸 an engine that loses its mind if two threads touch it at once
  • ♻️ a workload that needs explicit load / unload / recycle, not "hope the process survives"

AdaskoTheBeAsT.Interop.Execution is the reusable boilerplate you keep rewriting in every project: a dedicated worker thread (or a pool of them), a session it owns, a queue in front of it, and all the cancellation / disposal / telemetry plumbing that should just be a library by now. πŸ“¦

And now it is. ✨


Changelog

3.0.0

The version in Directory.Build.props is 3.0.0 across all four packages. This release upgrades the repository to .NET 11 (11.0.100) and C# 14, moves the multi-targeted matrix to net11.0, net10.0, net481, net48, and net472 (removing net8.0 and net9.0), introduces AdaskoTheBeAsT.Interop.Execution.AspNetCore (net11.0;net10.0), and adds contextual session lifecycle metadata, delegate session factories, IExecutionDispatcher<TSession> DI forwarding, validated IServiceProvider options, typed admission-rejection exceptions, dedicated worker-thread stack sizing and scopes, execution deadline extensions, and Hosting IHealthCheck support:

  • Contextual session lifecycle & DelegateExecutionSessionFactory<TSession>: SessionLifecycleContext, SessionRecycleReason, ContextualExecutionSessionFactory<TSession>, and DelegateExecutionSessionFactory<TSession> pass a stable WorkerIndex (0..WorkerCount - 1), WorkerCount, WorkerName, ManagedThreadId, PreviousRecycleReason, and matching SessionGeneration values to both CreateSession and DisposeSession, with single-lambda DI and Hosting registration overloads.
  • Ergonomic DI & Hosting registration: AddExecutionWorker<TSession> and AddExecutionWorkerPool<TSession> automatically forward IExecutionDispatcher<TSession> via TryAddSingleton, add Action<IServiceProvider, ...> and worker-indexed overloads (mirrored on AddExecutionWorkerHostedService<TSession> and AddExecutionWorkerPoolHostedService<TSession>), and validate options on startup via IValidateOptions<T> + .ValidateOnStart().
  • Worker-thread lifecycle & MaxStackSize: optional caller-side BeforeThreadStart plus dedicated-thread MaxStackSize, OnWorkerThreadStart, and worker-lifetime CreateWorkerThreadScope (IDisposable disposed on the same worker thread strictly after final DisposeSession()).
  • Typed ExecutionAdmissionRejectedException & execution deadlines: bounded QueueCapacity saturation throws ExecutionAdmissionRejectedException : InvalidOperationException carrying WorkerName and QueueCapacity, while ExecutionDispatcherExtensions bounds startup, queueing, and execution waits with TimeSpan timeout.
  • Hosting health checks & Execution.AspNetCore integration: extended ExecutionWorkerSnapshot / ExecutionWorkerPoolSnapshot readiness fields, built-in IHealthCheck registrations in Execution.Hosting, and a new AdaskoTheBeAsT.Interop.Execution.AspNetCore companion package (net11.0;net10.0) providing WithExecutionExceptionHandling, AddExecutionExceptionHandler, AOT-safe source-generated diagnostics DTOs (MapExecutionWorkerDiagnostics, MapExecutionWorkerPoolDiagnostics), and MapExecutionHealthProbes.
  • Target framework & dependency updates: added net11.0, removed net8.0 and net9.0, updated net11.0 and .NET Framework package ranges to [11.0.0, 12.0.0) and net10.0 Microsoft.Extensions.* ranges to [10.0.15, 11.0.0), and updated SDK (11.0.100), analyzer, and xunit.v3 (4.0.3) packages.

See the 2.x to 3.0.0 migration guide and the full changelog for release history.


Why upgrade to 2.0.0?

2.0.0 makes worker execution and shutdown more reliable and raises the minimum .NET Framework version to 4.7.2. Dropping net462, net47, and net471 is a breaking change and the reason for the major version. Existing integration APIs remain available on supported targets. The comparison below is against the tagged 1.0.0 release.

If your application... What could go wrong in 1.0.0 What 2.0.0 improves
Uses ExecuteValueAsync under load A caller could return a pooled source while the worker still used it; delegate failures bypassed worker recovery. Completion is the worker's last access to the item. Task and ValueTask requests share failure, cancellation, recycling, and outcome reporting.
Recycles native sessions A request could report success before required teardown finished. Awaiting the request includes recycle teardown. Cleanup failures become observable instead of looking like successful work.
Submits work before initialization finishes An async submission could block its calling thread on session creation. Submissions enqueue without waiting for creation and retain per-worker FIFO order. Startup failures settle the returned requests.
Shuts down from several places A repeated or reentrant disposal could make an external caller think teardown was already complete. Every external DisposeAsync() joins actual teardown, even after a synchronous disposal timeout.
Receives bursts of work Admission was unbounded. Opt into QueueCapacity to limit waiting requests and reject excess work explicitly, including during startup.
Needs a shutdown policy Pending-work handling was not an explicit choice. Choose Drain or CancelPending. Hosted shutdown also observes the host's cancellation deadline without canceling cleanup.
Relies on faults and tracing Fault handlers ran on the owning thread before Fault was published; listener errors could disrupt execution. Fault state is latched before off-thread notification. Listener exceptions are contained, and spans use the submitting request's activity context.
Reuses options or custom pool schedulers Later option mutations could alter live behavior; a scheduler could select a foreign concrete worker. Workers snapshot configuration, pools reject non-members, and partial pool construction rolls back earlier workers.

What is not new: pooled ExecuteValueAsync, DI/Hosting, session recycling, schedulers, snapshots, and scoped diagnostics already shipped in 1.0.0. This is a correctness and lifecycle upgrade, not a claim of faster native execution or a new benchmark result.

Before upgrading: applications targeting .NET Framework 4.6.2, 4.7, or 4.7.1 must retarget to 4.7.2 or later, or remain on 1.0.0. Modern .NET 8, 9, and 10 targets are unchanged.

On supported targets, existing public signatures are retained. The new options default to unlimited admission (QueueCapacity = 0) and Drain; applications receive the fixes without opting into queue limits. Completion timing, event ordering, and option validation do change, so review the 1.0.x to 2.0.0 migration guide before upgrading. See the changelog for release details.


✨ Why you'll love this

  • Pooled ValueTask path. ExecuteValueAsync reuses IValueTaskSource<T> work items on every supported TFM, including net472, avoiding a per-request source/Task allocation when a pooled item is available. This is not a guarantee of zero total allocations. (Completion contract)
  • DI + Hosting. Use AddExecutionWorker<TSession>() for plain DI, or AddExecutionWorkerHostedService<TSession>() to register both the worker and its hosted lifecycle.
  • πŸ’« Pluggable schedulers. LeastQueued and RoundRobin ship in the box; bring your own via IWorkerScheduler<TSession>. (ADR-0002)
  • πŸ”­ Batteries-included observability. ActivitySource + Meter with public constant names, ready for OpenTelemetry. (ADR-0003)
  • πŸͺŸ First-class Windows STA. Flip a boolean, get an STA worker thread on Windows; silently ignored elsewhere.
  • ♻️ Real session recycling. After N operations, after a failure, or both β€” your call.
  • πŸ›‘οΈ Terminal-once faulting. When a worker goes bad, it says so once, loudly, via WorkerFaulted β€” no silent-dead-thread surprises.
  • ⏱️ Built-in execution deadlines & health checks. Bound caller waits with TimeSpan extensions on IExecutionDispatcher<TSession> and wire readiness/degradation checks straight into AddHealthChecks().
  • 5 target frameworks. net11.0, net10.0, net481, net48, net472. .NET Framework 4.7.2 is the desktop minimum and .NET 10 is the modern .NET minimum in 3.0.0.
  • ✏️ Source Link + snupkg. Step into the library from your debugger without guessing.

πŸ“¦ Packages

Package What it gives you
AdaskoTheBeAsT.Interop.Execution βš“ Core: ExecutionWorker<TSession>, ExecutionWorkerPool<TSession>, IExecutionSessionFactory<TSession>, IContextualExecutionSessionFactory<TSession>, DelegateExecutionSessionFactory<TSession>, ExecutionAdmissionRejectedException, deadline extensions, options, schedulers, diagnostics.
AdaskoTheBeAsT.Interop.Execution.DependencyInjection 🧩 Microsoft.Extensions.DependencyInjection helpers: AddExecutionWorker<TSession>() / AddExecutionWorkerPool<TSession>() with automatic IExecutionDispatcher<TSession> forwarding, inline session delegates, worker-indexed resolvers, and ValidateOnStart IOptions<T> binding.
AdaskoTheBeAsT.Interop.Execution.Hosting πŸ—οΈ Microsoft.Extensions.Hosting & HealthChecks integration: IHostedService wrappers and IHealthCheck registrations driving worker / pool lifetime and readiness from the generic host.
AdaskoTheBeAsT.Interop.Execution.AspNetCore 🌐 ASP.NET Core Minimal API & ProblemDetails integration (net11.0;net10.0): WithExecutionExceptionHandling, AddExecutionExceptionHandler, AOT-safe source-generated diagnostics DTOs (MapExecutionWorkerDiagnostics, MapExecutionWorkerPoolDiagnostics), and MapExecutionHealthProbes.

⬇️ Install

dotnet add package AdaskoTheBeAsT.Interop.Execution
dotnet add package AdaskoTheBeAsT.Interop.Execution.DependencyInjection
dotnet add package AdaskoTheBeAsT.Interop.Execution.Hosting
dotnet add package AdaskoTheBeAsT.Interop.Execution.AspNetCore

Symbols ship as .snupkg with Source Link and embedded untracked sources. Step in. Look around. It's fine.


πŸ—ΊοΈ Target framework matrix

TFM Status Notes
net11.0 βœ… Primary target across all 4 packages; in-box System.Threading.Channels + System.Diagnostics.DiagnosticSource.
net10.0 βœ… Primary LTS target across all 4 packages.
net481 βœ… Windows desktop (Execution, DependencyInjection, Hosting); System.Threading.Channels + System.Diagnostics.DiagnosticSource via NuGet + IsExternalInit polyfill.
net48 βœ… Same as above.
net472 βœ… Same as above.

The five-target matrix applies to Execution, Execution.DependencyInjection, and Execution.Hosting, while Execution.AspNetCore targets net11.0 and net10.0 (Microsoft.AspNetCore.App). Removed in 3.0.0: net8.0 (.NET 8) and net9.0 (.NET 9); see the 2.x to 3.0.0 migration guide. Removed in 2.0.0: net462 (.NET Framework 4.6.2), net47 (4.7), and net471 (4.7.1); see the 1.0.x to 2.0.0 migration guide.

CI enables TreatWarningsAsErrors=true, ContinuousIntegrationBuild=true, and Deterministic=true. The four multi-targeted test projects target this same five-TFM matrix, while Execution.AspNetCore.Test targets net11.0 and net10.0.


πŸ’‘ The core idea

Instead of every interop-heavy engine reinventing:

  • a queue πŸ“‘
  • a worker thread 🧡
  • startup synchronisation πŸš€
  • session lifetime ⏳
  • disposal logic πŸ—‘οΈ
  • failure / recycle behaviour ♻️

...you park that generic machinery in ExecutionWorker<TSession> or ExecutionWorkerPool<TSession>. Your engine becomes a thin adapter that answers three questions:

  1. 🌱 How do I create a session?
  2. πŸ₯€ How do I dispose a session?
  3. πŸ› οΈ What work should run on that session?

That's it. The rest is the library's problem now.

                        β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
   ExecuteAsync(x) ──▢  β”‚   Channel<ExecutionWorkItem> β”‚
                        β”‚   (multi-writer, 1 reader)   β”‚
                        β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
                                       β”‚
                                       β–Ό
                            β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
                            β”‚  Dedicated Thread     β”‚
                            β”‚  owns ONE TSession    β”‚  ◀──  STA on Windows
                            β”‚  runs work in FIFO    β”‚        if you ask
                            β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
                                        β”‚
                                        β–Ό
                                β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
                                β”‚  TSession   β”‚  (native libs, COM, ...)
                                β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜

πŸ“š Main types

βš™οΈ ExecutionWorker<TSession>

A single dedicated background thread that owns one TSession. Submitted work runs sequentially in FIFO order. Implements IDisposable and IAsyncDisposable.

Owns πŸ‘‡

  • a multi-writer / single-reader Channel of work items
  • one dedicated background Thread (optionally STA on Windows)
  • startup / shutdown lifecycle (InitializeAsync(CancellationToken) + sync Initialize)
  • configurable draining or cancellation of pending items on shutdown
  • session reuse + session recycle after failure or after N operations
  • observability via Name, IsFaulted, Fault, QueueDepth, WorkerFaulted, and the uniform GetSnapshot()

βš™οΈβš™οΈβš™οΈβš™οΈ ExecutionWorkerPool<TSession>

Fan-out pool of ExecutionWorker<TSession> instances. Each pool worker owns a private session and a private queue; a pluggable IWorkerScheduler<TSession> picks which worker receives each submission.

Owns πŸ‘‡

  • multiple ExecutionWorker<TSession> instances
  • pluggable work distribution (see Scheduling below)
  • one session per worker (ideal for isolated native DLL sets)
  • separate worker-owned sessions (process-global native state still needs adapter-level isolation)
  • parallel initialization and parallel disposal
  • aggregate observability (QueueDepth, IsAnyFaulted, WorkerFaults, forwarded WorkerFaulted, and per-worker snapshots via GetSnapshot().Workers)

🏭 IExecutionSessionFactory<TSession>, IContextualExecutionSessionFactory<TSession>, and DelegateExecutionSessionFactory<TSession>

public interface IExecutionSessionFactory<TSession>
    where TSession : class
{
    TSession CreateSession(CancellationToken cancellationToken);
    void DisposeSession(TSession session);
}

Creates the thread-affine session (loading native libs, initialising modules) and disposes / unloads it. Both methods run on the dedicated worker thread.

Need the stable worker slot (0..WorkerCount - 1), pool size, session generation (0, 1, 2, ...), or previous recycle reason (MaxOperationsReached / OperationFaulted)? Implement IContextualExecutionSessionFactory<TSession> (or subclass ContextualExecutionSessionFactory<TSession>): CreateSession and DisposeSession receive the same SessionLifecycleContext.SessionGeneration for a given session lifetime.

Don't want to write a custom factory class just to invoke a constructor and Dispose()? Use DelegateExecutionSessionFactory<TSession> (or the inline delegate overloads in DI and Hosting):

var factory = new DelegateExecutionSessionFactory<NativeSession>(
    (context, ct) => new NativeSession(context.WorkerIndex));
// Automatically checks ct.ThrowIfCancellationRequested() and calls (session as IDisposable)?.Dispose().

πŸŽ›οΈ ExecutionWorkerOptions

Name, UseStaThread, MaxStackSize (0 = runtime default, > 0 = dedicated thread stack reservation in bytes), MaxOperationsPerSession (0 = unlimited), DisposeTimeout (default Timeout.InfiniteTimeSpan), Diagnostics (scoped ExecutionDiagnostics instance β€” defaults to a process-wide Shared singleton), BeforeThreadStart (optional callback invoked synchronously on the caller before creating and starting the worker thread), OnWorkerThreadStart (invoked once on the dedicated worker thread after ApartmentState is set and before initial CreateSession), and CreateWorkerThreadScope (Func<IDisposable?>? invoked once on the dedicated worker thread before initial CreateSession, surviving session recyclings, and disposed on that exact worker thread strictly after the final DisposeSession()). Parameterless ctor + positional ctor + public setters + public Validate() so it binds cleanly via IOptions<T>.

QueueCapacity limits requests waiting for startup or execution (0 = unlimited). ShutdownMode selects Drain (default) or CancelPending. Options are validated and copied when the worker is constructed; later mutations do not reconfigure it.

πŸŽ›οΈ ExecutionWorkerPoolOptions

WorkerCount, Name, UseStaThread, MaxStackSize, MaxOperationsPerSession, DisposeTimeout, SchedulingStrategy (default LeastQueued), Diagnostics, BeforeThreadStart (invoked synchronously once per pool startup attempt before any worker thread is created), OnWorkerThreadStart (Action<int>? receiving workerIndex), and CreateWorkerThreadScope (Func<int, IDisposable?>? receiving workerIndex). Same binding and Validate() story.

QueueCapacity and ShutdownMode apply to each worker. Pool options are also copied at construction. Capacity is per worker, not a shared pool-wide limit.

πŸŽ›οΈ ExecutionRequestOptions

Per-call knob: RecycleSessionOnFailure (default false).


πŸͺŸ STA behavior

If UseStaThread: true is set:

  • βœ… On Windows, the worker thread is configured as STA via SetApartmentState(ApartmentState.STA) (guarded by OperatingSystem.IsWindows() on net5+ and PlatformID.Win32NT on older TFMs).
  • 🀷 On non-Windows, the flag is silently ignored.

That makes the option safe for cross-platform callers that want "STA when possible" behaviour.

The worker does not run a COM or UI message pump. STA alone is insufficient for components that require one. Separate worker sessions also do not isolate process-global native state; the adapter must supply any required process-wide serialization or process isolation.

Startup, admission, cancellation, and shutdown

  • Submit synchronous delegates only. An async lambda can escape the owning thread and outlive its session. Do not synchronously wait for nested work on the same worker.
  • Async submissions return without waiting for initial session creation. Work is queued in FIFO order on each worker, including during startup.
  • InitializeAsync(token) cancels only that caller's wait. Shared startup continues for other callers. Disposing the worker separately requests cancellation of initial session creation.
  • A full QueueCapacity faults the submission with ExecutionAdmissionRejectedException (which derives from InvalidOperationException and exposes WorkerName and QueueCapacity); it does not block or silently drop work. The executing request is excluded from the limit. A pool does not retry another worker after capacity rejection.
  • A request canceled before execution is skipped when dequeued. Once running, its delegate must observe its own token. Neither request cancellation nor shutdown forcibly interrupts managed or native code.
  • Drain completes queued work on an available session. CancelPending skips requests not yet started. Both let running delegates finish before teardown. If initial creation is canceled or fails, queued requests cannot run and are completed with cancellation or failure.
  • Every external DisposeAsync() joins the same actual teardown. A call from the owning worker only requests shutdown, avoiding a self-deadlock. Synchronous Dispose() can abandon its wait at DisposeTimeout; cleanup continues and a later DisposeAsync() still joins it.
  • Hosted StopAsync(token) uses the host deadline to bound its wait, not the cleanup itself. If the token fires before teardown completes, awaiting StopAsync throws OperationCanceledException. Container disposal may still wait for a blocked native call.

Hard deadlines and recovery from a hung native call require a separate process. See ADR-0010 for the ownership and compatibility decisions.


πŸš€ Quick example

This complete console example uses top-level statements on modern .NET. The session is a stub; replace Render and the factory cleanup with your native API.

using System.Text;
using AdaskoTheBeAsT.Interop.Execution;

CancellationToken cancellationToken = CancellationToken.None;

// 1. Spin up the worker.
await using var worker = new ExecutionWorker<NativeSession>(
    new NativeSessionFactory(),
    new ExecutionWorkerOptions(
        name: "Native Render Worker",
        useStaThread: true,
        maxOperationsPerSession: 500));

await worker.InitializeAsync(cancellationToken);

// 2. Throw work at it. Returns when the work item completes.
byte[] bytes = await worker.ExecuteAsync(
    (session, ct) =>
    {
        ct.ThrowIfCancellationRequested();
        return session.Render("<h1>Hello</h1>");
    },
    new ExecutionRequestOptions(recycleSessionOnFailure: true),
    cancellationToken);

Console.WriteLine($"Produced {bytes.Length} bytes.");

public sealed class NativeSession
{
    public byte[] Render(string html) => Encoding.UTF8.GetBytes(html);
}

public sealed class NativeSessionFactory : IExecutionSessionFactory<NativeSession>
{
    public NativeSession CreateSession(CancellationToken cancellationToken)
    {
        cancellationToken.ThrowIfCancellationRequested();
        return new NativeSession();
    }

    public void DisposeSession(NativeSession session)
    {
        // Free native handles here, on the owning worker thread.
    }
}

Pooled ValueTask hot path

Both the IExecutionWorker<TSession> and IExecutionWorkerPool<TSession> interfaces and the concrete ExecutionWorker<TSession> and ExecutionWorkerPool<TSession> types expose instance ExecuteValueAsync overloads backed by pooled IValueTaskSource<T> work items on every supported TFM. Use the same synchronous delegate as with ExecuteAsync; only the returned completion type changes.

byte[] bytes = await worker.ExecuteValueAsync(
    (session, ct) =>
    {
        ct.ThrowIfCancellationRequested();
        return session.Render("<h1>Hello</h1>");
    },
    cancellationToken: cancellationToken);

Await each returned ValueTask exactly once. If you need to share or repeatedly await a result, use ExecuteAsync, or call AsTask() once and retain that Task. Do not discard, double-await, or synchronously read an incomplete ValueTask.

Pooling avoids per-request source/Task allocations when an item can be reused; startup, pool misses, delegates, channels, continuations, and tracing can still allocate. The pooling API already existed in 1.0.0. The 2.0.0 improvement is safe completion ownership and the same recovery behavior as the Task path. See ADR-0010, which supersedes the lifecycle design in ADR-0007.

Execution deadlines (TimeSpan timeout)

ExecutionDispatcherExtensions provides ExecuteAsync and ExecuteValueAsync extension overloads with a TimeSpan timeout on IExecutionDispatcher<TSession>:

byte[] bytes = await worker.ExecuteAsync(
    (session, ct) =>
    {
        ct.ThrowIfCancellationRequested();
        return session.Render("<h1>Hello</h1>");
    },
    timeout: TimeSpan.FromSeconds(2),
    cancellationToken: cancellationToken);

The deadline bounds startup, queueing, and execution. Queued work that expires before dequeue never runs; deadline expiry throws TimeoutException, while caller cancellation throws OperationCanceledException with the caller's exact CancellationToken. If a synchronous native call is already running when the deadline fires, the caller returns promptly while the worker stays occupied until the native call completes.


🏭🏭🏭🏭 Pool: multiple workers

If one worker is not enough, use ExecutionWorkerPool<TSession>. Great fit when:

  • πŸ“ you have several native library copies in separate folders
  • πŸ“¦ each worker should load its own isolated DLL set
  • ♻️ one failed worker session should recycle without touching the others
  • 🏎️ you want several dedicated threads, but still serialised execution per worker
await using var pool = new ExecutionWorkerPool<NativePoolSession>(
    workerIndex => new NativePoolSessionFactory($@"c:\native\slot-{workerIndex + 1:D2}"),
    new ExecutionWorkerPoolOptions(
        workerCount: 4,
        name: "Native Pool",
        useStaThread: true,
        maxOperationsPerSession: 250));

await pool.InitializeAsync(cancellationToken);

var result = await pool.ExecuteAsync(
    (session, ct) => session.Render("<h1>Hello from pool</h1>"),
    new ExecutionRequestOptions(recycleSessionOnFailure: true),
    cancellationToken);

πŸ’‘ Tip: need every worker to share the exact same factory? There's a single-factory constructor overload too: new ExecutionWorkerPool<T>(factory, options). Nice and tidy for stateless factories. (ADR-0008)


🚦 Scheduling

The pool ships with two built-in schedulers and a public IWorkerScheduler<TSession> seam if you need something bespoke.

Built-in Icon Semantics
LeastQueuedWorkerScheduler<TSession> (default) βš–οΈ Picks the healthy worker with the smallest QueueDepth. Ties break via a shared rolling index so equal-depth workers rotate. Skips faulted workers. Early-exits when it finds a zero-depth worker.
RoundRobinWorkerScheduler<TSession> πŸ”„ Strict rotation across healthy workers via an Interlocked index. Skips faulted workers.

Swap built-ins via options, or plug in a custom scheduler via the pool ctor:

// Option A: pick a built-in via options.
var opts = new ExecutionWorkerPoolOptions(
    workerCount: 4,
    schedulingStrategy: SchedulingStrategy.RoundRobin);

// Option B: inject a custom scheduler.
IWorkerScheduler<NativeSession> custom = new MyAffinityScheduler();
await using var pool = new ExecutionWorkerPool<NativeSession>(
    workerIndex => new NativeSessionFactory(),
    new ExecutionWorkerPoolOptions(workerCount: 4),
    custom);

Rationale, trade-offs, and the faulted-worker contract are captured in ADR-0002.


πŸ€” When to use what

1️⃣ Choose ExecutionWorker<TSession> when

  • πŸ”’ the native engine is effectively process-global
  • πŸ₯΅ the library is known to be thread-sensitive
  • β›” you want strict serialised access to one engine instance
  • πŸ‘‘ you want exactly one owner thread

4️⃣ Choose ExecutionWorkerPool<TSession> when

  • πŸ‘€πŸ‘€πŸ‘€πŸ‘€ you have isolated native copies per worker
  • 🏎️🏎️ the library can run in parallel across separate worker-owned sessions
  • πŸš€ you want better throughput
  • πŸ”§ you want one worker to recycle independently from the others

♻️ Session recycle story

You can choose to recycle the session:

  • ❌ after a failed request β€” ExecutionRequestOptions.RecycleSessionOnFailure = true
  • πŸ’― after a fixed number of operations β€” ExecutionWorkerOptions.MaxOperationsPerSession > 0
  • ✨ or both

Set maxOperationsPerSession: 0 when you want unlimited session lifetime and only failure-based recycling.

Task and ValueTask calls use the same failure and recycle policy. Completion is published only after any required session teardown. A teardown error after a successful delegate faults the request and worker. If the delegate also failed, its exception remains the request failure and Fault records the terminal teardown error. A canceled request does not count as a successful operation or trigger failure-based recycling.


🧩 DI integration

using AdaskoTheBeAsT.Interop.Execution;
using AdaskoTheBeAsT.Interop.Execution.DependencyInjection;

// Option A: class-based session factory
services.AddSingleton<IExecutionSessionFactory<NativeSession>, NativeSessionFactory>();
services.AddExecutionWorker<NativeSession>(options =>
{
    options.Name = "Native Render Worker";
    options.UseStaThread = true;
    options.MaxOperationsPerSession = 500;
});

// Option B: inline session delegate + IServiceProvider-aware options (validated on start)
services.AddExecutionWorkerPool<NativeSession>(
    (sp, ctx, ct) => new NativeSession(ctx.WorkerIndex),
    (sp, options) =>
    {
        var cfg = sp.GetRequiredService<IOptions<HostPoolSettings>>().Value;
        options.WorkerCount = cfg.WorkerCount;
        options.QueueCapacity = cfg.QueueCapacity;
    });

// Resolve IExecutionDispatcher<NativeSession>, IExecutionWorker<NativeSession>,
// or IExecutionWorkerPool<NativeSession> from DI and use it as usual.

Both AddExecutionWorker<TSession> and AddExecutionWorkerPool<TSession> automatically forward IExecutionDispatcher<TSession> via TryAddSingleton and wire IValidateOptions<T> + .ValidateOnStart() so invalid option values fail fast at host startup. AddExecutionWorkerPool<TSession> resolves IContextualExecutionSessionFactory<TSession> when registered (falling back to IExecutionSessionFactory<TSession>), resolves an optional IWorkerScheduler<TSession>, and also offers worker-indexed ((sp, workerIndex) => ...) and inline-delegate ((sp, ctx, ct) => ...) overloads.


πŸ—οΈ Generic host & health-check integration

using AdaskoTheBeAsT.Interop.Execution.Hosting;

services.AddSingleton<IExecutionSessionFactory<NativeSession>, NativeSessionFactory>();
services.AddExecutionWorkerHostedService<NativeSession>(options =>
{
    options.Name = "Native Render Worker";
    options.UseStaThread = true;
});

services.AddHealthChecks()
    .AddExecutionWorkerHealthCheck<NativeSession>(
        configure: health => health.QueueDepthWarningThreshold = 16,
        tags: ["ready"]);

The registration includes the worker, IExecutionDispatcher<TSession> forwarding, and its IHostedService wrapper; you do not need a separate AddExecutionWorker<TSession>() call. Both DI and Hosting also support inline createSession delegates (DelegateExecutionSessionFactory<TSession>) and Action<IServiceProvider, ...> option callbacks with .ValidateOnStart(). The wrapper drives InitializeAsync on StartAsync and joins DisposeAsync on StopAsync. In 2.0.0+, a canceled stop token cancels only that wait, not worker cleanup. Repeated stops join the same teardown, subject to each caller's token. AddExecutionWorkerPoolHostedService<TSession> and AddExecutionWorkerPoolHealthCheck<TSession> cover the pool (reporting Unhealthy before eager initialization completes, after disposal, or when all workers fault, and Degraded on partial worker loss or elevated queue depth).


🌐 ASP.NET Core Minimal API integration

using AdaskoTheBeAsT.Interop.Execution.AspNetCore;
using AdaskoTheBeAsT.Interop.Execution.Hosting;

builder.Services.AddExecutionAspNetCoreJson();
builder.Services.AddExecutionWorkerPoolHostedService<NativeSession>(
    (sp, ctx, ct) => new NativeSession(ctx.WorkerIndex),
    (sp, options) =>
    {
        options.WorkerCount = 4;
        options.QueueCapacity = 32;
    });
builder.Services.AddHealthChecks()
    .AddExecutionWorkerPoolHealthCheck<NativeSession>(tags: ["ready"]);

var app = builder.Build();
app.MapExecutionHealthProbes(); // /healthz + /readyz
app.MapExecutionWorkerPoolDiagnostics<NativeSession>(); // AOT-safe /api/diagnostics

app.MapPost("/api/calculate", async (
        CalcRequest req,
        IExecutionDispatcher<NativeSession> dispatcher,
        CancellationToken ct) =>
    TypedResults.Ok(await dispatcher.ExecuteValueAsync(
        (session, token) => session.Calculate(req, token),
        TimeSpan.FromSeconds(5),
        ct)))
    .WithExecutionExceptionHandling("Native engine unavailable.");

WithExecutionExceptionHandling (available on both RouteHandlerBuilder and RouteGroupBuilder, alongside the optional global builder.Services.AddExecutionExceptionHandler(...) + app.UseExceptionHandler() pipeline) maps:

  • ArgumentException β†’ 400 Bad Request ProblemDetails using ExecutionAspNetCoreOptions.BadRequestTitle (never echoing internal native paths or stack traces).
  • OperationCanceledException when HttpContext.RequestAborted is canceled β†’ 499 Client Closed Request.
  • TimeoutException, ExecutionAdmissionRejectedException, or ObjectDisposedException β†’ 503 Service Unavailable ProblemDetails using ExecutionAspNetCoreOptions.UnavailableTitle and an optional ceiling-rounded Retry-After header (ExecutionAspNetCoreOptions.RetryAfter).

MapExecutionWorkerDiagnostics<TSession> and MapExecutionWorkerPoolDiagnostics<TSession> project snapshots through source-generated DTOs (ExecutionWorkerDiagnosticsDto / ExecutionWorkerPoolDiagnosticsDto backed by ExecutionAspNetCoreJsonSerializerContext, exposing faultType instead of raw System.Exception) so /api/diagnostics remains Native-AOT-safe and leak-free even when workers fault. MapExecutionHealthProbes wires /healthz (zero-check liveness) and /readyz ("ready"-tagged readiness) in a single call.


πŸ”­ Observability

Every worker emits to an ActivitySource and Meter named AdaskoTheBeAsT.Interop.Execution (customisable per worker via ExecutionWorkerOptions.Diagnostics β€” see ADR-0009 for scoped emitters).

Instrument Kind Tags
ExecutionWorker.Execute πŸ“‘ Activity (span) worker.name
execution.worker.operations πŸ“ˆ Counter<long> worker.name, outcome ∈ success / faulted / cancelled
execution.worker.session_recycles πŸ“ˆ Counter<long> worker.name, reason ∈ max_operations / failure
execution.worker.queue_depth πŸ“‰ ObservableGauge<int> worker.name

All these identifiers are exposed as public const string on ExecutionDiagnosticNames, so telemetry pipelines can subscribe without hard-coding strings:

using AdaskoTheBeAsT.Interop.Execution;
using OpenTelemetry.Trace;
using OpenTelemetry.Metrics;

builder.Services.AddOpenTelemetry()
    .WithTracing(t => t.AddSource(ExecutionDiagnosticNames.SourceName))
    .WithMetrics(m => m.AddMeter(ExecutionDiagnosticNames.SourceName));

When no activity listener is attached, StartActivity returns null and no execution span is created. This does not guarantee allocation-free execution.

See ADR-0003 for why the identifiers are a public contract.


⚠️ Faulting semantics

ExecutionWorker<TSession> is terminal-once: a session creation or teardown failure latches Fault before WorkerFaulted is queued to the thread pool. Subscribers run off the owning thread; throwing subscribers are contained. Notification is asynchronous and may arrive after disposal completes. The first terminal exception wins, and the worker cannot be re-initialised.

A delegate exception alone faults that request, optionally recycling its session. An OperationCanceledException is cancellation only when the request token was canceled; otherwise it is a failure for both Task and ValueTask calls. Future submissions rethrow a terminal fault synchronously unless disposal has already been requested, in which case they throw ObjectDisposedException.

Disposal joins teardown without rethrowing terminal session errors. Inspect Fault, IsFaulted, or WorkerFaulted for those errors. Diagnostic-listener exceptions do not fail requests; execution spans use the submitting activity as their parent.

Pool consumers observe the same contract aggregated: IsAnyFaulted, WorkerFaults, and a forwarded WorkerFaulted event carrying the originating worker name. πŸ””


πŸ” Migrating

  • From 2.x to 3.0.0: see the 3.0.0 migration guide. Retarget any net8.0 or net9.0 projects to net10.0 or net11.0; on net11.0, net10.0, net481, net48, and net472, existing 2.2.0 APIs remain source- and binary-compatible.
  • From 1.0.x to 2.0.0: see the 2.0.0 migration guide. It covers retargeting from .NET Framework < 4.7.2, before/after completion and fault ordering, option snapshots, QueueCapacity, and ShutdownMode.

πŸ§ͺ Build and test

dotnet build .\AdaskoTheBeAsT.Interop.slnx
dotnet test --solution .\AdaskoTheBeAsT.Interop.slnx --no-build
Project Role
test/unit/AdaskoTheBeAsT.Interop.Execution.Test πŸ”¬ Unit + behavioural (fault propagation, dispose idempotency, cancellation, deadlines, contextual & delegate factories, ExecutionAdmissionRejectedException, BeforeThreadStart, MaxStackSize, OnWorkerThreadStart, CreateWorkerThreadScope, telemetry smoke, scheduler contract).
test/unit/AdaskoTheBeAsT.Interop.Execution.DependencyInjection.Test 🧩 DI registration, IExecutionDispatcher<TSession> forwarding, IServiceProvider options + ValidateOnStart, contextual/indexed/delegate factory resolution.
test/unit/AdaskoTheBeAsT.Interop.Execution.Hosting.Test πŸ—οΈ IHostedService start/stop lifecycle, idempotent registration/shutdown, startup option validation, worker/pool IHealthCheck transitions.
test/unit/AdaskoTheBeAsT.Interop.Execution.AspNetCore.Test 🌐 Minimal API TestServer filter/exception-handler status mappings (200/400/499/503), strict source-generated /api/diagnostics under faults, and /healthz + /readyz probes (net11.0;net10.0).
test/integ/AdaskoTheBeAsT.Interop.Execution.IntegrationTest 🀝 Multi-threaded submission, STA on Windows, reentrant dispose, multi-pool contextual session recycling, zero-alloc ValueTask, snapshot surface, scoped diagnostics.

The four core test projects target net11.0, net10.0, net481, net48, and net472, and Execution.AspNetCore.Test targets net11.0 and net10.0.


πŸ“œ Architecture Decision Records

Small, self-contained design decisions taken on this codebase live under docs/adr/. Start with the index. Highlights:


πŸ™‹ Contributing

Found a bug? Got an idea? Spotted a typo that's been haunting you? πŸ‘»

  1. πŸ™ Open an issue describing the problem or the proposal.
  2. πŸ› οΈ Fork + branch (feature/your-idea).
  3. βœ… Run dotnet build + dotnet test across the full matrix.
  4. ✨ Add/update tests and an ADR if the change is load-bearing.
  5. πŸš€ Open a PR β€” the strict-build + CI will do the rest.

πŸ“š Further reading


<p align="center"> Built for the kind of interop code that likes <strong>one owner thread</strong>, <strong>explicit lifecycle</strong>, and <strong>zero drama</strong>. ✨<br/> Made with ❀️ (and a lot of coffee β˜•) by <a href="https://github.com/AdaskoTheBeAsT">AdaskoTheBeAsT</a>. </p>

Product Compatible and additional computed target framework versions.
.NET net10.0 is compatible.  net10.0-android was computed.  net10.0-browser was computed.  net10.0-ios was computed.  net10.0-maccatalyst was computed.  net10.0-macos was computed.  net10.0-tvos was computed.  net10.0-windows was computed.  net11.0 is compatible. 
.NET Framework net472 is compatible.  net48 is compatible.  net481 is compatible. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

NuGet packages (3)

Showing the top 3 NuGet packages that depend on AdaskoTheBeAsT.Interop.Execution.Hosting:

Package Downloads
AdaskoTheBeAsT.WkHtmlToX.Hosting

Microsoft.Extensions.Hosting integration for AdaskoTheBeAsT.WkHtmlToX: AddWkHtmlToXHostedService() registers an IHostedService that drives the WkHtmlToX engine worker lifecycle through the generic host.

AdaskoTheBeAsT.Interop.Execution.AspNetCore

ASP.NET Core minimal-API and diagnostics integration for AdaskoTheBeAsT.Interop.Execution: endpoint filters and IExceptionHandler mapping execution timeouts, capacity rejections, disposal, client disconnects, and argument errors to ProblemDetails, AOT-safe leak-free worker/pool diagnostics DTOs and JsonSerializerContext, and /healthz + /readyz probe mapping. Targets net11.0 and net10.0.

AdaskoTheBeAsT.YaraX.Interop

Managed .NET native interop wrapper (MIT) with bundled YARA-X native libraries (BSD 3-Clause), zero-downtime hot-reloadable rules provider, hosted thread-affine scanning worker pool, and YARA Forge rule sync (Windows x64, Linux glibc x64, Alpine musl x64).

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last Updated
3.1.0 178 11/22/2026
3.0.0 154 11/21/2026
2.2.0 217 10/24/2026
2.1.0 171 9/9/2026
2.0.0 160 9/7/2026
1.0.0 319 4/19/2026

## [3.0.0]

Upgrades the solution to .NET 11 (`11.0.100`) and C# 14, updates the supported
target framework matrix to `net11.0`, `net10.0`, `net481`, `net48`, and
`net472`, introduces the companion `AdaskoTheBeAsT.Interop.Execution.AspNetCore`
package (`net11.0;net10.0`), and adds contextual session lifecycle metadata,
delegate session factories, worker-indexed and `IServiceProvider`-aware DI /
Hosting registration with `IExecutionDispatcher<TSession>` forwarding and
`ValidateOnStart`, typed admission-rejection exceptions, dedicated worker-thread
stack sizing and thread-affine lifecycle scopes, execution deadline extensions,
and Hosting `IHealthCheck` support.

**Breaking change:** `.NET 8` (`net8.0`) and `.NET 9` (`net9.0`) support has
been removed, `.NET 11` (`net11.0`) has been added, and package dependency
floors move to `11.0.0` (on `net11.0` and `.NET Framework`) and `10.0.15` (on
`net10.0`). On retained targets, existing `2.2.0` public signatures remain
source- and binary-compatible. See the
[2.x to 3.0.0 migration guide](docs/migration-3.0.0.md) for upgrade steps.

### Removed

- **`.NET 8` (`net8.0`) and `.NET 9` (`net9.0`) target frameworks** from the
 three multi-targeted packages and four multi-targeted test projects. The
 supported five-target matrix is `net11.0`, `net10.0`, `net481`, `net48`, and
 `net472` (`AdaskoTheBeAsT.Interop.Execution.AspNetCore` targets `net11.0` and
 `net10.0`).

### Added

- **Contextual session lifecycle (`EX-01`):**
 `SessionLifecycleContext`, `SessionRecycleReason` (`MaxOperationsReached`,
 `OperationFaulted`), `IContextualExecutionSessionFactory<TSession>` (deriving
 from `IExecutionSessionFactory<TSession>`), and the abstract
 `ContextualExecutionSessionFactory<TSession>` base class. Contextual factories
 receive a stable `WorkerIndex` (`0` for standalone workers, `0..WorkerCount-1`
 in pools), `WorkerCount`, `WorkerName`, `ManagedThreadId`,
 `PreviousRecycleReason`, and the same `SessionGeneration` across matching
 `CreateSession` and `DisposeSession` calls, incrementing `SessionGeneration`
 only after a session or replacement is successfully created.
- **Worker-indexed DI and Hosting overloads (`EX-01`):**
 `AddExecutionWorkerPool<TSession>(Func<IServiceProvider, int, IExecutionSessionFactory<TSession>>, ...)`
 in `AdaskoTheBeAsT.Interop.Execution.DependencyInjection` and
 `AddExecutionWorkerPoolHostedService<TSession>(Func<IServiceProvider, int, IExecutionSessionFactory<TSession>>, ...)`
 in `AdaskoTheBeAsT.Interop.Execution.Hosting`, plus automatic resolution of
 `IContextualExecutionSessionFactory<TSession>` ahead of
 `IExecutionSessionFactory<TSession>` in standard worker and pool DI
 registrations.
- **Execution deadline extension overloads (`EX-03`):**
 `ExecutionDispatcherExtensions` adds `ExecuteAsync` and `ExecuteValueAsync`
 (void and `TResult`, with and without `ExecutionRequestOptions`) overloads
 accepting `TimeSpan timeout` on `IExecutionDispatcher<TSession>`. Deadlines
 bound startup, queueing, and execution waits without adding abstract interface
 members; queued expired items never run; caller cancellation preserves the
 exact caller `CancellationToken` while deadline expiry throws
 `TimeoutException`; in-flight synchronous native work keeps the worker/session
 occupied and retains its linked cancellation source until completion before
 reusing uncancelled `CancellationTokenSource` instances on `.NET 6+`.
- **Hosting health checks and readiness snapshot fields (`EX-04`):**
 extended `ExecutionWorkerSnapshot` (`IsInitialized`, `IsDisposed`) and
 `ExecutionWorkerPoolSnapshot` (`IsInitialized`, `IsDisposed`,
 `InitializedWorkerCount`, `FaultedWorkerCount`) while preserving existing
 constructors, and added `ExecutionHealthCheckOptions`,
 `ExecutionWorkerHealthCheck<TSession>`,
 `ExecutionWorkerPoolHealthCheck<TSession>`,
 `AddExecutionWorkerHealthCheck<TSession>`, and
 `AddExecutionWorkerPoolHealthCheck<TSession>` in
 `AdaskoTheBeAsT.Interop.Execution.Hosting`. Health checks report `Unhealthy`
 before eager initialization finishes, after disposal, on startup/total worker
 faults, `Degraded` on partial pool worker loss or when `QueueDepth` reaches
 `QueueDepthWarningThreshold`, and `Healthy` otherwise.
- **Pre-thread startup callback (`EX-06`):**
 optional `Action? BeforeThreadStart` on `ExecutionWorkerOptions` and
 `ExecutionWorkerPoolOptions` (propagated through option snapshots and DI).
 Runs synchronously on the caller before dedicated worker threads are created,
 configured for STA, and started, running once per pool startup attempt before
 any worker thread spawns.
- **Typed `ExecutionAdmissionRejectedException` (`EX-07`):**
 `public sealed class ExecutionAdmissionRejectedException : InvalidOperationException`
 carrying `WorkerName`, `QueueCapacity`, and `DefaultMessage`
 (`"The worker admission capacity is exhausted."`), emitted by both
 `ExecutionWorker<TSession>` and `ExecutionWorkerPool<TSession>` across `Task`
 and `ValueTask` submissions when `QueueCapacity > 0` is saturated (with
 `.NET Framework` `[Serializable]` round-trip support).
- **Automatic `IExecutionDispatcher<TSession>` forwarding and validated
 `IServiceProvider` options in DI and Hosting (`EX-08`):**
 `AddExecutionWorker<TSession>` and `AddExecutionWorkerPool<TSession>` now
 forward `IExecutionDispatcher<TSession>` via `TryAddSingleton`, add
 `Action<IServiceProvider, ExecutionWorkerOptions>` and
 `Action<IServiceProvider, ExecutionWorkerPoolOptions>` overloads (mirrored on
 `AddExecutionWorkerHostedService<TSession>` and
 `AddExecutionWorkerPoolHostedService<TSession>`), expose public `Validate()`
 methods on `ExecutionWorkerOptions` and `ExecutionWorkerPoolOptions`, and wire
 `IValidateOptions<T>` with `.ValidateOnStart()` so invalid options fail fast
 during `IHost.StartAsync`.
- **`DelegateExecutionSessionFactory<TSession>` and inline delegate DI/Hosting
 registration (`EX-09`):**
 `DelegateExecutionSessionFactory<TSession>` (deriving from
 `ContextualExecutionSessionFactory<TSession>`) supports simple and contextual
 session creation/disposal lambdas with automatic `(session as IDisposable)?.Dispose()`
 fallback, paired with inline `createSession` / `disposeSession` registration
 overloads in `Execution.DependencyInjection` and `Execution.Hosting`.
- **Companion `AdaskoTheBeAsT.Interop.Execution.AspNetCore` package (`EX-10`,
 `net11.0;net10.0`):**
 zero-third-party-dependency ASP.NET Core integration shipping
 `ExecutionAspNetCoreOptions`, `ExecutionEndpointFilter`
 (`WithExecutionExceptionHandling` on `RouteHandlerBuilder` and
 `RouteGroupBuilder`), `ExecutionExceptionHandler : IExceptionHandler`
 (`AddExecutionExceptionHandler`), AOT-safe source-generated
 `ExecutionWorkerDiagnosticsDto` and `ExecutionWorkerPoolDiagnosticsDto`
 (`FaultType` instead of raw `Exception`, avoiding `MethodBase` serialization
 failures and stack-trace leaks), `ExecutionAspNetCoreJsonSerializerContext`,
 `AddExecutionAspNetCoreJson()`, `MapExecutionWorkerDiagnostics<TSession>()`,
 `MapExecutionWorkerPoolDiagnostics<TSession>()`, and
 `MapExecutionHealthProbes()`.
- **Worker-thread `MaxStackSize`, `OnWorkerThreadStart`, and
 `CreateWorkerThreadScope` (`EX-11`):**
 configurable dedicated-thread `MaxStackSize` (`>= 0`) plus once-per-thread
 `OnWorkerThreadStart` (`Action?` / `Action<int>?`) and worker-lifetime
 `CreateWorkerThreadScope` (`Func<IDisposable?>?` /
 `Func<int, IDisposable?>?`) on `ExecutionWorkerOptions` and
 `ExecutionWorkerPoolOptions`, running on the dedicated STA/MTA thread before
 initial session creation, surviving session recyclings, and disposing on the
 same worker thread strictly after final `DisposeSession()`.
- [2.x to 3.0.0 migration guide](docs/migration-3.0.0.md) and Architecture
 Decision Records [ADR-0011](docs/adr/0011-net11-target-framework-matrix.md),
 [ADR-0012](docs/adr/0012-contextual-session-lifecycle.md),
 [ADR-0013](docs/adr/0013-before-thread-start-hook.md),
 [ADR-0014](docs/adr/0014-execution-deadline-extensions.md),
 [ADR-0015](docs/adr/0015-hosting-health-checks-and-readiness-snapshots.md),
 [ADR-0016](docs/adr/0016-typed-admission-rejected-exception.md),
 [ADR-0017](docs/adr/0017-dispatcher-forwarding-and-validated-di-options.md),
 [ADR-0018](docs/adr/0018-delegate-execution-session-factory.md),
 [ADR-0019](docs/adr/0019-aspnetcore-execution-integration-and-safe-diagnostics.md),
 and [ADR-0020](docs/adr/0020-worker-thread-stack-size-and-thread-affine-scopes.md).

### Changed

- Updated `global.json` to `.NET SDK 11.0.100` with
 `Microsoft.Testing.Platform`, `<LangVersion>14.0</LangVersion>`, and package
 version `3.0.0` in `Directory.Build.props`.
- Updated `.NET Framework` package dependencies (`System.Threading.Channels`,
 `System.Diagnostics.DiagnosticSource`, and `Microsoft.Extensions.*`) and
 `net11.0` `Microsoft.Extensions.*` dependencies to `[11.0.0, 12.0.0)`, raised
 `net10.0` `Microsoft.Extensions.*` floors to `[10.0.15, 11.0.0)`, and added
 `Microsoft.Extensions.Diagnostics.HealthChecks` to
 `AdaskoTheBeAsT.Interop.Execution.Hosting`.
- Updated analyzer and test-project dependencies (`Meziantou.Analyzer`
 `3.0.341`, `Microsoft.CodeAnalysis.*` `5.12.0`,
 `Microsoft.CodeAnalysis.NetAnalyzers` `11.0.100`, `SonarAnalyzer.CSharp`
 `10.36.0.15337`, `StyleCop.Analyzers` `1.3.180`, `Microsoft.NET.Test.Sdk`
 `18.12.0`, `Microsoft.Testing.Extensions.GitHubActionsReport` `2.5.3`,
 `xunit.v3` `4.0.3`, and `xunit.analyzers` `2.3.0`).

### Regression coverage

- Unit and integration tests across `net11.0`, `net10.0`, `net481`, `net48`, and
 `net472` (plus `net11.0` and `net10.0` for `Execution.AspNetCore.Test`) cover
 contextual lifecycle generations, `DelegateExecutionSessionFactory`, failure
 handling, two concurrent STA/MTA pools over 50+ recycles per slot,
 `BeforeThreadStart`, `MaxStackSize`, `OnWorkerThreadStart`, and
 `CreateWorkerThreadScope` ordering/affinity, eager startup readiness
 (`EX-02`), CAS `QueueCapacity` admission and typed
 `ExecutionAdmissionRejectedException` (`EX-05`, `EX-07`), deadline
 boundary/cancellation/race semantics, `IExecutionDispatcher<TSession>` DI
 forwarding and `ValidateOnStart` (`EX-08`), Hosting health-check state
 transitions, and ASP.NET Core `TestServer` filter/exception-handler HTTP
 mappings and strict source-generated `/api/diagnostics` serialization under
 worker faults (`EX-10`).