# Ownership and cleanup

Source: https://libtmux.org/en/csharp/latest/topics/context-managers/

> Scope-based cleanup for tmux objects, and when your program must kill them explicitly.

A tmux session, window, or pane normally remains until you kill it. Scope-based
cleanup can kill it when your code leaves a block, including after an exception.
See [Workspaces](https://libtmux.org/en/csharp/latest/concepts/workspaces/) for a temporary layout example.

<a id="net-an-explicit-ownership-type-stopping-at-window"></a>

## Owned sessions and windows

C#'s [`OwnedSessionScope`](<https://libtmux.org/en/csharp/latest/reference/libtmux-ownedsessionscope/>) and [`OwnedWindowScope`](<https://libtmux.org/en/csharp/latest/reference/libtmux-ownedwindowscope/>) wrap the created object and
implement [`IAsyncDisposable`](<https://learn.microsoft.com/dotnet/api/system.iasyncdisposable>). The [`Session`](<https://libtmux.org/en/csharp/latest/reference/libtmux-session/>) and [`Window`](<https://libtmux.org/en/csharp/latest/reference/libtmux-window/>) handles themselves are
not disposable:

```csharp
await using OwnedSessionScope session = await server.CreateOwnedSessionAsync();
await using OwnedWindowScope window = await session.Value.CreateOwnedWindowAsync();

await window.Value.SendTextAsync("echo hello");
// window, then session, killed on the way out
```

For tests that need an owned pane,
[`TmuxTestFactory.CreateHierarchyAsync()`](<https://libtmux.org/en/csharp/latest/reference/libtmux-testing-tmuxtestfactory-createhierarchyasync/>) returns a [`TemporaryHierarchyScope`](<https://libtmux.org/en/csharp/latest/reference/libtmux-testing-temporaryhierarchyscope/>)
containing a private server, session, window, and pane. Disposing it kills the
server.

<a id="what-this-means-in-practice"></a>

## Testing cleanup

Use explicit cleanup for objects whose handles have no disposal hook. For an
entire disposable test server, prefer your port's test fixture or server guard;
see [Testing with libtmux](https://libtmux.org/en/csharp/latest/guides/testing-with-libtmux/).
