Cette page n'est pas encore traduite. La version anglaise est affichée ci-dessous.

SBK2001: Pooled buffer never returned

Analyzer SnowBank.Core
Severity Warning (performance)
Code fix Yes

Message

'{0}' rents a buffer from a pool and is never disposed, so the buffer never returns. Declare it with 'using'.

Why

new SliceWriter(pool), new PooledSliceWriter(...), new PooledSliceAllocator(...), SliceOwner.Create(...), SliceOwner.Copy(...), Slice.FromBytes(span, pool), and writer.ToSliceOwner() rent an array from an ArrayPool<byte>. The array goes back to the pool only when the writer, allocator, or owner is disposed. A local that is never disposed keeps the array out of the pool, so the pool rents a fresh one to the next caller and the rented arrays pile up.

The rule reports a local initialized with one of those expressions when it is not declared with using, no Dispose(), Release(), or ToSliceOwner() is called on it in the method, and it does not leave the method (not returned, not stored in a field or a property, not passed to another method, not copied into another local). new SliceWriter() and new SliceWriter(capacity) write to a heap array and are not reported.

Bad

var writer = new SliceWriter(ArrayPool<byte>.Shared);
writer.WriteInt32(1);
Send(writer.GetBytes());

Good

using var writer = new SliceWriter(ArrayPool<byte>.Shared);
writer.WriteInt32(1);
Send(writer.GetBytes());

Code fix

The fix adds using to the declaration.

Suppress

#pragma warning disable SBK2001 // reason

or, for a whole project, in .editorconfig:

dotnet_diagnostic.SBK2001.severity = none

The whole performance tier can be muted at once:

dotnet_analyzer_diagnostic.category-SnowBankPerformance.severity = none