C#C
C#10mo ago
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");
}


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?
Was this page helpful?