© 2026 Hedgehog Software, LLC

TwitterGitHubDiscord
More
CommunitiesDocsAboutTermsPrivacy
Search
Star
Setup for Free
C#C
C#•16mo ago•
40 replies
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; }
}
[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?
C# banner
C#Join
We are a programming server aimed at coders discussing everything related to C# (CSharp) and .NET.
61,871Members
Resources

Similar Threads

Was this page helpful?
Recent Announcements

Similar Threads

Is it worth to use AsNoTracking in dbset?
C#CC# / help
3y ago
✅ Is it possible to use grouping here?
C#CC# / help
3y ago
✅ Is it worth to use record in this situation?
C#CC# / help
3y ago
Is it possible to use pattern matching here?
C#CC# / help
15mo ago