C
C#2mo 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");
}
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?
5 Replies
Yawnder
Yawnder2mo ago
Any reason why you want to do that rather than using the HttpClientFactory?
many things
many things2mo ago
are you using this for sse/websocket?
SWEETPONY
SWEETPONYOP2mo ago
yes, sse
many things
many things2mo ago
have you already discarded using signalr?
SWEETPONY
SWEETPONYOP2mo ago
it is impossible to use signalr here

Did you find this page helpful?