C#C
C#14mo ago
SWEETPONY

✅ Is it worth to use stackalloc here?

Hey, I have this:
[HttpGet("stream")]
public async Task StreamHeartbeatAsync(CancellationToken cancellationToken)
{
    Response.Headers.Append("Content-Type", "text/event-stream");
    Response.Headers.Append("Cache-Control", "no-cache");
    Response.Headers.Append("Connection", "keep-alive");

    while(!cancellationToken.IsCancellationRequested)
    {
        var sseEvent = new SseEvent<object>
        {
            Action = SseAction.Heartbeat,
            Timestamp = DateTime.UtcNow
        };

        await Response.WriteAsJsonAsync(sseEvent, cancellationToken);
        await Response.Body.FlushAsync(cancellationToken);

        await Task.Delay(sseSettings.Timeout, cancellationToken);
    }
}

public sealed class SseEvent<T>
{
    public required DateTime Timestamp { get; set; }
    public required SseAction Action { get; set; }
    public string? Store { get; set; }
    public string? Identity { get; set; }
    public T? Data { get; set; }
}


I think it is not good to create sseEvent every second without any memory clean. Is it worth to use stackalloc here?
Was this page helpful?