Start/Stop Patterns
Control server lifecycle: blocking vs non‑blocking, programmatic shutdown.
Full source
File: pwsh/tutorial/examples/15.1-Start-Stop.ps1
<#
15.1 Start / Stop Patterns
#>
param(
[int]$Port = 5000,
[IPAddress]$IPAddress = [IPAddress]::Loopback
)
New-KrLogger | Add-KrSinkConsole | Register-KrLogger -Name 'console' -SetAsDefault | Out-Null
# 2. Create server host
$srv = New-KrServer -Name 'Lifecycle Demo' -PassThru
# 3. Add loopback listener on port 5000 (auto unlinks existing file if present)
# This listener will be used to demonstrate server limits configuration.
Add-KrEndpoint -Port $Port -IPAddress $IPAddress
# 6. Finalize configuration and set server limits
Enable-KrConfiguration
# 7. Map a simple info route to demonstrate server options in action
Add-KrMapRoute -Verbs Get -Pattern '/status' -ScriptBlock {
Write-KrLog -Level Debug -Message 'Health check'
Write-KrJsonResponse -InputObject @{ status = 'healthy' }
}
# 8. Start the server (runs asynchronously; press Ctrl+C to stop)
Start-KrServer -Server $srv -NoWait
Write-KrLog -Level Information -Message 'Server started (non-blocking).'
Write-Host 'Server running for 30 seconds'
Start-Sleep 30
Stop-KrServer -Server $srv
Write-KrLog -Level Information -Message 'Server stopped.'
Close-KrLogger
Step-by-step
- Create server with
-PassThruto retain object. - Add listener/runtime & enable config.
- Map
/healthroute. - Start non‑blocking:
Start-KrServer -NoWait. - Perform work (press Enter) then call
Stop-KrServer. - Remove server to clean resources.
Patterns
| Pattern | How |
|---|---|
| Blocking | Start-KrServer (Ctrl+C) |
| Non-blocking | Start-KrServer -NoWait + later Stop-KrServer |
| Programmatic | Maintain server object (-PassThru) |
Try it
# Start non-blocking
pwsh .\docs\_includes\examples\pwsh\15.1-Start-Stop.ps1
# In another terminal, hit health
Invoke-RestMethod http://127.0.0.1:5000/health
References
- Start-KrServer
- Stop-KrServer
- Remove-KrServer
- New-KrServer
- Add-KrEndpoint
- Enable-KrConfiguration
- Add-KrMapRoute
Troubleshooting
| Symptom | Cause | Fix |
|---|---|---|
| Cannot stop | Missing reference | Capture server with -PassThru |
| Hanging exit | Pending requests | Allow active requests to finish or force stop |
Previous / Next
Previous: Server Options Next: Demos