Packet Pooling

Read time 2 minutes Package: Nalix.Runtime
On this page

Nalix.Codec.Pooling provides packet-specific pooling helpers for reusable packet instances.

Source mapping

  • src/Nalix.Codec/Pooling/PacketFactory.cs
  • src/Nalix.Codec/Pooling/PacketScope.cs

Main types

  • PacketFactory<TPacket>
  • PacketScope<TPacket>

Public members at a glance

TypePublic members
PacketScope<TPacket>Value, IsValid, Dispose(), implicit operator TPacket(PacketScope<TPacket>)
PacketFactory<TPacket>Acquire()

PacketScope<TPacket>

PacketScope<TPacket> is a zero-allocation readonly struct that ensures a rented packet is returned to its pool upon disposal.

Disposing the scope returns the packet to its originating pool.

That makes it a good fit when you want a short-lived packet object without manually returning it yourself.

Practical notes

  • the scope wraps exactly one packet instance
  • the packet is returned when the scope is disposed
  • use using or using var so the pool release happens even if later code throws

PacketFactory<TPacket>

PacketFactory<TPacket> is the static pool API for a specific packet type.

It provides:

  • Acquire() — rents a packet and wraps it in a PacketScope<TPacket>

Practical notes

  • Acquire() is the safest option — the returned scope automatically returns the packet on dispose
  • for startup warm-up or pool reset, use ObjectPoolManager.Prealloc<T>() and ObjectPoolManager.ClearPool<T>() directly

Common pitfalls

  • forgetting to dispose a scope
  • using a packet reference after its scope has been disposed
  • keeping a pooled packet reference alive after it was returned

Basic usage

using PacketScope<Control> scope = PacketFactory<Control>.Acquire();
Control packet = scope.Value;
packet.Type = ControlType.PING;

When to use which

NeedStart with
Automatic return to the poolPacketScope<TPacket> via PacketFactory<T>.Acquire()
Startup warm-upObjectPoolManager.Prealloc<T>(count)
Pool reset or teardownObjectPoolManager.ClearPool<T>()