© 2026 Hedgehog Software, LLC

TwitterGitHubDiscord
More
CommunitiesDocsAboutTermsPrivacy
Search
Star
Setup for Free
C#C
C#•11mo ago•
5 replies
SWEETPONY

✅ How to make httpcontext threadsafe?

I have this:
public sealed record UserConnectionModel
{
    private readonly CancellationTokenSource cancellationTokenSource;

    public UserConnectionModel(CancellationTokenSource cancellationTokenSource)
    {
        this.cancellationTokenSource = cancellationTokenSource;
        AddedDateTime = DateTime.Now;
    }

    public required string SessionId { get; init; }

    public required string ConnectionId { get; init; }

    public required string ResourceIdentity { get; init; }

    public IReadOnlyCollection<string> ResourceGroupIdentities { get; init; } = [];

    public DateTime AddedDateTime { get; init; }

    public DateTime? DisconnectedDateTime { get; set; }

    public required int TimezoneOffset { get; set; }

    public required HttpContext ConnectionContext { get; init; }

    public Task CloseConnectionAsync() => cancellationTokenSource.CancelAsync();

    public Task SendEventAsync(object data) => ConnectionContext.Response.WriteAsync($"data: {data}\n\n");
}
public sealed record UserConnectionModel
{
    private readonly CancellationTokenSource cancellationTokenSource;

    public UserConnectionModel(CancellationTokenSource cancellationTokenSource)
    {
        this.cancellationTokenSource = cancellationTokenSource;
        AddedDateTime = DateTime.Now;
    }

    public required string SessionId { get; init; }

    public required string ConnectionId { get; init; }

    public required string ResourceIdentity { get; init; }

    public IReadOnlyCollection<string> ResourceGroupIdentities { get; init; } = [];

    public DateTime AddedDateTime { get; init; }

    public DateTime? DisconnectedDateTime { get; set; }

    public required int TimezoneOffset { get; set; }

    public required HttpContext ConnectionContext { get; init; }

    public Task CloseConnectionAsync() => cancellationTokenSource.CancelAsync();

    public Task SendEventAsync(object data) => ConnectionContext.Response.WriteAsync($"data: {data}\n\n");
}


I save these connections to ConcurrentDictionary, and when I need to send a message, I just find the connection from the dictionary and use SendEventAsync.
I don't know why, but sometimes I don't see that any events have been sent, and it looks like a race condition. What can I do about it?
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

How to locally loadbalance threadsafe [Answered]
C#CC# / help
4y ago
Threadsafe async code design
C#CC# / help
5mo ago
HttpContext and TraceIdentifier
C#CC# / help
2y ago
HttpContext.Current doesn't exist
C#CC# / help
4y ago