Fix fire'n'forget task from blocking guest logins.

This commit is contained in:
Lucas Morgan
2023-07-07 16:46:26 -05:00
parent dacd0475f9
commit 8884d15d6e
4 changed files with 42 additions and 24 deletions

View File

@@ -14,16 +14,16 @@ public class ShogiSocket : IDisposable
public event AsyncEventHandler<SessionJoinedByPlayerSocketMessage>? OnSessionJoined;
public event AsyncEventHandler<PlayerHasMovedMessage>? OnPlayerMoved;
private readonly ClientWebSocket socket;
private ClientWebSocket socket;
private readonly JsonSerializerOptions serializerOptions;
private readonly UriBuilder uriBuilder;
private readonly CancellationTokenSource cancelToken;
private readonly IMemoryOwner<byte> memoryOwner;
private bool disposedValue;
public ShogiSocket(IConfiguration configuration, ClientWebSocket socket, JsonSerializerOptions serializerOptions)
public ShogiSocket(IConfiguration configuration, JsonSerializerOptions serializerOptions)
{
this.socket = socket;
this.socket = new ClientWebSocket();
this.serializerOptions = serializerOptions;
this.uriBuilder = new UriBuilder(configuration["SocketUrl"] ?? throw new InvalidOperationException("SocketUrl configuration is missing."));
this.cancelToken = new CancellationTokenSource();
@@ -36,22 +36,30 @@ public class ShogiSocket : IDisposable
{
await this.socket.CloseAsync(WebSocketCloseStatus.NormalClosure, "Closing before opening a new connection.", CancellationToken.None);
}
if (this.socket.State == WebSocketState.Closed)
{
this.socket.Dispose();
this.socket = new ClientWebSocket(); // Because you can't reopen a closed socket.
}
else
{
Console.WriteLine("Opening socket and existing socket state is " + this.socket.State.ToString());
}
uriBuilder.Query = new QueryBuilder { { "token", token } }.ToQueryString().Value;
Console.WriteLine("ShogiSocket.OpenAsync socket state is {0}", this.socket.State.ToString());
await socket.ConnectAsync(this.uriBuilder.Uri, cancelToken.Token);
// Fire and forget! I'm way too lazy to write my own javascript interop to a web worker. Nooo thanks.
_ = Listen().ContinueWith(async antecedent =>
{
this.cancelToken.Cancel();
await this.socket.CloseAsync(WebSocketCloseStatus.NormalClosure, "Page was probably closed or refresh.", CancellationToken.None);
if (antecedent.Exception != null)
_ = Listen()
.ContinueWith(async antecedent =>
{
throw antecedent.Exception;
}
}, TaskContinuationOptions.OnlyOnFaulted);
this.cancelToken.Cancel();
await this.socket.CloseAsync(WebSocketCloseStatus.NormalClosure, "Page was probably closed or refresh.", CancellationToken.None);
if (antecedent.Exception != null)
{
throw antecedent.Exception;
}
}, TaskContinuationOptions.OnlyOnFaulted)
.ConfigureAwait(false);
}
private async Task Listen()