improvement: Accept CancellationToken in JsonRpcRequestObservable
This commit is contained in:
1 parent
23771909fd
commit
eff979fb2b
1 file changed
+6
-3
@@ -7,14 +7,17 @@ using mbts.utils;
|
||||
using Microsoft.Extensions.Logging;
|
||||
|
||||
using System.Net.WebSockets;
|
||||
using System.Runtime.CompilerServices;
|
||||
using System.Text;
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Nodes;
|
||||
|
||||
public class JsonRpcRequestAsyncEnumerable {
|
||||
public static async IAsyncEnumerable<JsonRpcRequest<JsonNode>> Create(WebSocket webSocket, ILogger logger, int bufferCapacity = 4096, CancellationToken? cancellationToken = null) {
|
||||
public static IAsyncEnumerable<JsonRpcRequest<JsonNode>> Create(WebSocket webSocket, ILogger logger, CancellationToken cancellationToken) =>
|
||||
Create(webSocket, logger, 4096, cancellationToken);
|
||||
|
||||
public static async IAsyncEnumerable<JsonRpcRequest<JsonNode>> Create(WebSocket webSocket, ILogger logger, int bufferCapacity, [EnumeratorCancellation]CancellationToken cancellationToken) {
|
||||
ExceptionAssert.Argument.GreaterThanEqualTo(bufferCapacity, 0);
|
||||
cancellationToken ??= CancellationToken.None;
|
||||
var buffer = new byte[bufferCapacity];
|
||||
var offset = 0;
|
||||
for (var res = await Recv(); res is not null && !res.CloseStatus.HasValue; res = await Recv()) {
|
||||
@@ -35,7 +38,7 @@ public class JsonRpcRequestAsyncEnumerable {
|
||||
async Task<WebSocketReceiveResult?> Recv() {
|
||||
var offsetBuffer = new ArraySegment<byte>(buffer, offset, buffer.Length - offset);
|
||||
try {
|
||||
return await webSocket.ReceiveAsync(offsetBuffer, cancellationToken.Value);
|
||||
return await webSocket.ReceiveAsync(offsetBuffer, cancellationToken);
|
||||
} catch (TaskCanceledException) {
|
||||
logger.LogTrace("JsonRpcRequestAsyncEnumerable 'ReceiveAsync' task was cancelled (exiting gracefully).");
|
||||
} catch (Exception ex) {
|
||||
|
||||
Reference in new issue
Block a user