Skip to content

[API Proposal]: IDistributedCache overloads with ReadOnlyMemory<byte> support #70137

Closed
@kerams

Description

@kerams

Background and motivation

IDistributedCache.Set and SetAsync only take a byte array as the input. This is not ideal when working with oversized pooled arrays for example, because you need to reallocate the data out into a fixed-size array just to pass it into the cache. Having overloads with ReadOnlyMemory<byte> parameters would alleviate this issue (supposing the actual caching implementation itself supports Memory, which StackExchange.Redis does).

API Proposal

Additions to Microsoft.Extensions.Caching.Distributed.IDistributedCache:

void Set(string key, ReadOnlyMemory<byte> value, DistributedCacheEntryOptions options);
Task SetAsync(string key, ReadOnlyMemory<byte> value, DistributedCacheEntryOptions options, CancellationToken token = default(CancellationToken));

API Usage

public static async Task Cache(string key, string looongString, IDistributedCache cache, DistributedCacheEntryOptions options)
{
    var maxLength = Encoding.UTF8.GetMaxByteCount(looongString.Length);
    var pooled = ArrayPool<byte>.Shared.Rent(maxLength);

    try
    {
        var bytesWritten = Encoding.UTF8.GetBytes(looongString, pooled);
        await cache.SetAsync(key, pooled.AsMemory(0, bytesWritten), options);
    }
    finally
    {
        ArrayPool<byte>.Shared.Return(pooled);
    }
}

Alternative Designs

No response

Risks

No response

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions