Server.CreateOwnedAsync
Starts a server and takes ownership of it.
Source and package
- Module
- LibTmux
- Declared in
- Server
- Package
- LibTmux
- Source
- src/LibTmux/Server.Lifecycle.cs
- CreateOwnedAsync ( options : Server
Connection ? , cancellationToken : CancellationOptions Token ) Task<OwnedServer >Scope -
Description#
The scope holds an endpoint rather than a materialized server, because a tmux server with no sessions exits at once.
Valuestays that endpoint after a session is created through it; its session, window, and pane listings andCaptureSnapshotAsyncdiscover the live server on each call, and the objects they return carry the discovered handle.On the default socket, the one a caller gets by naming none, a server already listening is refused rather than adopted: disposing the scope stops the server, and on a developer's machine the default socket holds the one they are using. A named socket or path stays the caller's to adopt deliberately. The check and the start are two tmux calls, so two callers that own the default socket at the same moment can both pass it; give each owned server a socket of its own.
A call that fails or is cancelled after starting a server stops it, since no scope reaches the caller to do so; a server it found running is left.
Examples#
Distinguish an endpoint handle from a discovered server. Connection discovery returns an immutable replacement without capturing child relations. Use Linux or macOS with Git, tmux 3.2a or newer, .NET SDK 10.0.303, and the .NET 8 and 10 runtimes. In an empty directory, fetch the documented library revision:
Terminal window $ git clone https://github.com/libtmux/libtmux-dotnet.git libtmux-source && \git -C libtmux-source checkout --detach cf34b255c896d19a97e7d7fabea58609c916012dSave this complete consumer setup as global.json: View source
{"sdk": {"version": "10.0.303","rollForward": "disable","allowPrerelease": false},"test": {"runner": "Microsoft.Testing.Platform"}}Save this complete consumer setup as NuGet.config: View source
<?xml version="1.0" encoding="utf-8"?><configuration><packageSources><clear /><add key="libtmux-source" value="libtmux-source/artifacts/api-example-packages" /><add key="nuget.org" value="https://api.nuget.org/v3/index.json" /></packageSources><packageSourceMapping><clear /><packageSource key="libtmux-source"><package pattern="LibTmux" /><package pattern="LibTmux.*" /></packageSource><packageSource key="nuget.org"><package pattern="*" /></packageSource></packageSourceMapping></configuration>Save this complete consumer setup as Example.csproj: View source
<Project Sdk="Microsoft.NET.Sdk"><PropertyGroup><OutputType>Exe</OutputType><TargetFrameworks>net8.0;net10.0</TargetFrameworks><LangVersion>12.0</LangVersion><Nullable>enable</Nullable><ImplicitUsings>disable</ImplicitUsings><EnableDefaultCompileItems>false</EnableDefaultCompileItems><TreatWarningsAsErrors>true</TreatWarningsAsErrors><AnalysisLevel>10-recommended</AnalysisLevel></PropertyGroup><ItemGroup><Compile Include="Program.cs" /><PackageReference Include="LibTmux" Version="[0.0.0-alpha.20]" /></ItemGroup></Project>Save this complete program as Program.cs. It creates a private server; await using disposes its owned scopes after success, cancellation or failure. The complete file contains explicit imports, a top-level async entry point and a cancellation deadline. View source
using System;using System.Threading;using LibTmux;if (OperatingSystem.IsWindows()){throw new PlatformNotSupportedException("This example requires tmux on Linux or macOS.");}using CancellationTokenSource deadline = new(TimeSpan.FromSeconds(10));CancellationToken token = deadline.Token;string binary = Environment.GetEnvironmentVariable("LIBTMUX_TMUX") ?? "tmux";string socketName = "csharp-serverconstruction-" + Guid.NewGuid().ToString("N");ServerConnectionOptions options = new(){SocketName = socketName,ConfigurationFile = "/dev/null",TmuxBinaryPath = binary,};// Open records the endpoint without running tmux or reading its state.Server endpoint = Server.Open(options);if (endpoint.IsMaterialized){throw new InvalidOperationException("Open must not discover a server.");}await using OwnedServerScope owned = await Server.CreateOwnedAsync(options, token);await using OwnedSessionScope session = await owned.Value.CreateOwnedSessionAsync(new NewSessionRequest { Name = "demo", Command = "/bin/cat" }, token);// Connect discovers the live daemon and returns a new materialized handle.Server connected = await endpoint.ConnectAsync(token);Server sameEndpoint = await Server.ConnectAsync(options, token);if (!connected.IsMaterialized || !sameEndpoint.IsMaterialized || endpoint.IsMaterialized){throw new InvalidOperationException("Connecting must leave the original handle unchanged.");}if (connected.Generation != sameEndpoint.Generation || connected.Sessions.IsCaptured){throw new InvalidOperationException("Connection discovery must not capture the hierarchy.");}Console.WriteLine("Open records an endpoint; Connect discovers the running server.");Console.WriteLine("The original handle stays unmaterialized; relations remain uncaptured.");Build the exact source package and the saved consumer, then run both supported frameworks. The local package feed prevents an unrelated published package from satisfying the restore. Each program checks its result and exits unsuccessfully after an unhandled error:
Terminal window $ export NUGET_PACKAGES="$PWD/packages" && \dotnet restore libtmux-source/src/LibTmux/LibTmux.csproj --locked-mode && \dotnet pack libtmux-source/src/LibTmux/LibTmux.csproj \--configuration Release --no-restore -p:ContinuousIntegrationBuild=true \--output "$PWD/libtmux-source/artifacts/api-example-packages" && \dotnet restore Example.csproj --configfile NuGet.config && \dotnet build Example.csproj --configuration Release --no-restore --warnaserror && \export LIBTMUX_TMUX="$(command -v tmux)" && \export TMUX_TMPDIR=/tmp/libtmux-dotnet-dev && \mkdir -p "$TMUX_TMPDIR" && \unset TMUX TMUX_PANE && \dotnet bin/Release/net8.0/Example.dll && \dotnet bin/Release/net10.0/Example.dllExpected program output from each framework:
Open records an endpoint; Connect discovers the running server.The original handle stays unmaterialized; relations remain uncaptured.- Parameters
-
-
options ( Server
Connection ? ) – Connection options.Options -
cancellationToken ( Cancellation
Token ) – Cancels the tmux commands.
-
- Returns
-
A scope that stops the server when disposed.
- Raises
-
-
Invalid
Operation – A server is already listening on the default socket.Exception -
Tmux
Command – tmux failed to say whether a server is listening, such as on a socket it may not open.Exception
-
Discussed in Testing with libtmux · Use the C# workspace builder