1
0
mirror of https://github.com/JKorf/CryptoExchange.Net synced 2026-04-13 00:22:22 +00:00

Compare commits

..

5 Commits

7 changed files with 252 additions and 50 deletions

View File

@ -6,9 +6,9 @@
<PackageId>CryptoExchange.Net</PackageId> <PackageId>CryptoExchange.Net</PackageId>
<Authors>JKorf</Authors> <Authors>JKorf</Authors>
<Description>CryptoExchange.Net is a base library which is used to implement different cryptocurrency (exchange) API's. It provides a standardized way of implementing different API's, which results in a very similar experience for users of the API implementations.</Description> <Description>CryptoExchange.Net is a base library which is used to implement different cryptocurrency (exchange) API's. It provides a standardized way of implementing different API's, which results in a very similar experience for users of the API implementations.</Description>
<PackageVersion>10.6.2</PackageVersion> <PackageVersion>10.7.0</PackageVersion>
<AssemblyVersion>10.6.2</AssemblyVersion> <AssemblyVersion>10.7.0</AssemblyVersion>
<FileVersion>10.6.2</FileVersion> <FileVersion>10.7.0</FileVersion>
<PackageRequireLicenseAcceptance>false</PackageRequireLicenseAcceptance> <PackageRequireLicenseAcceptance>false</PackageRequireLicenseAcceptance>
<PackageTags>OKX;OKX.Net;Mexc;Mexc.Net;Kucoin;Kucoin.Net;Kraken;Kraken.Net;Huobi;Huobi.Net;CoinEx;CoinEx.Net;Bybit;Bybit.Net;Bitget;Bitget.Net;Bitfinex;Bitfinex.Net;Binance;Binance.Net;CryptoCurrency;CryptoCurrency Exchange;CryptoExchange.Net</PackageTags> <PackageTags>OKX;OKX.Net;Mexc;Mexc.Net;Kucoin;Kucoin.Net;Kraken;Kraken.Net;Huobi;Huobi.Net;CoinEx;CoinEx.Net;Bybit;Bybit.Net;Bitget;Bitget.Net;Bitfinex;Bitfinex.Net;Binance;Binance.Net;CryptoCurrency;CryptoCurrency Exchange;CryptoExchange.Net</PackageTags>
<RepositoryType>git</RepositoryType> <RepositoryType>git</RepositoryType>

View File

@ -1,4 +1,5 @@
using CryptoExchange.Net.Objects; using CryptoExchange.Net.Objects;
using CryptoExchange.Net.Objects.Options;
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
@ -105,31 +106,36 @@ namespace CryptoExchange.Net
/// <summary> /// <summary>
/// Create a new HttpMessageHandler instance /// Create a new HttpMessageHandler instance
/// </summary> /// </summary>
public static HttpMessageHandler CreateHttpClientMessageHandler(ApiProxy? proxy, TimeSpan? keepAliveInterval) public static HttpMessageHandler CreateHttpClientMessageHandler(RestExchangeOptions options)
{ {
#if NET5_0_OR_GREATER #if NET5_0_OR_GREATER
var socketHandler = new SocketsHttpHandler(); var socketHandler = new SocketsHttpHandler();
try try
{ {
if (keepAliveInterval != null && keepAliveInterval != TimeSpan.Zero) if (options.HttpKeepAliveInterval != null && options.HttpKeepAliveInterval != TimeSpan.Zero)
{ {
socketHandler.KeepAlivePingPolicy = HttpKeepAlivePingPolicy.Always; socketHandler.KeepAlivePingPolicy = HttpKeepAlivePingPolicy.Always;
socketHandler.KeepAlivePingDelay = keepAliveInterval.Value; socketHandler.KeepAlivePingDelay = options.HttpKeepAliveInterval.Value;
socketHandler.KeepAlivePingTimeout = TimeSpan.FromSeconds(10); socketHandler.KeepAlivePingTimeout = TimeSpan.FromSeconds(10);
} }
socketHandler.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate; socketHandler.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;
socketHandler.DefaultProxyCredentials = CredentialCache.DefaultCredentials; socketHandler.DefaultProxyCredentials = CredentialCache.DefaultCredentials;
socketHandler.EnableMultipleHttp2Connections = options.HttpEnableMultipleHttp2Connections;
socketHandler.PooledConnectionLifetime = options.HttpPooledConnectionLifetime;
socketHandler.PooledConnectionIdleTimeout = options.HttpPooledConnectionIdleTimeout;
socketHandler.MaxConnectionsPerServer = options.HttpMaxConnectionsPerServer;
} }
catch (PlatformNotSupportedException) { } catch (PlatformNotSupportedException) { }
catch (NotImplementedException) { } // Mono runtime throws NotImplementedException catch (NotImplementedException) { } // Mono runtime throws NotImplementedException
if (proxy != null) if (options.Proxy != null)
{ {
socketHandler.Proxy = new WebProxy socketHandler.Proxy = new WebProxy
{ {
Address = new Uri($"{proxy.Host}:{proxy.Port}"), Address = new Uri($"{options.Proxy.Host}:{options.Proxy.Port}"),
Credentials = proxy.Password == null ? null : new NetworkCredential(proxy.Login, proxy.Password) Credentials = options.Proxy.Password == null ? null : new NetworkCredential(options.Proxy.Login, options.Proxy.Password)
}; };
} }
return socketHandler; return socketHandler;
@ -143,12 +149,12 @@ namespace CryptoExchange.Net
catch (PlatformNotSupportedException) { } catch (PlatformNotSupportedException) { }
catch (NotImplementedException) { } // Mono runtime throws NotImplementedException catch (NotImplementedException) { } // Mono runtime throws NotImplementedException
if (proxy != null) if (options.Proxy != null)
{ {
httpHandler.Proxy = new WebProxy httpHandler.Proxy = new WebProxy
{ {
Address = new Uri($"{proxy.Host}:{proxy.Port}"), Address = new Uri($"{options.Proxy.Host}:{options.Proxy.Port}"),
Credentials = proxy.Password == null ? null : new NetworkCredential(proxy.Login, proxy.Password) Credentials = options.Proxy.Password == null ? null : new NetworkCredential(options.Proxy.Login, options.Proxy.Password)
}; };
} }
return httpHandler; return httpHandler;

View File

@ -32,10 +32,29 @@ namespace CryptoExchange.Net.Objects.Options
#else #else
= new Version(1, 1); = new Version(1, 1);
#endif #endif
/// <summary> /// <summary>
/// Http client keep alive interval for keeping connections open /// Http client keep alive interval for keeping connections open. Only applied when using dotnet8.0 or higher and dependency injection
/// </summary> /// </summary>
public TimeSpan? HttpKeepAliveInterval { get; set; } = TimeSpan.FromSeconds(15); public TimeSpan? HttpKeepAliveInterval { get; set; } = TimeSpan.FromSeconds(15);
#if NET5_0_OR_GREATER
/// <summary>
/// Enable multiple simultaneous HTTP 2 connections. Only applied when using dependency injection
/// </summary>
public bool HttpEnableMultipleHttp2Connections { get; set; } = false;
/// <summary>
/// Lifetime of pooled HTTP connections; the time before a connection is recreated. Only applied when using dependency injection
/// </summary>
public TimeSpan HttpPooledConnectionLifetime { get; set; } = TimeSpan.FromMinutes(15);
/// <summary>
/// Idle timeout of pooled HTTP connections; the time before an open connection is closed when there are no requests. Only applied when using dependency injection
/// </summary>
public TimeSpan HttpPooledConnectionIdleTimeout { get; set; } = TimeSpan.FromMinutes(2);
/// <summary>
/// Max number of connections per server. Only applied when using dependency injection
/// </summary>
public int HttpMaxConnectionsPerServer { get; set; } = int.MaxValue;
#endif
/// <summary> /// <summary>
/// Set the values of this options on the target options /// Set the values of this options on the target options
@ -54,6 +73,12 @@ namespace CryptoExchange.Net.Objects.Options
item.CachingMaxAge = CachingMaxAge; item.CachingMaxAge = CachingMaxAge;
item.HttpVersion = HttpVersion; item.HttpVersion = HttpVersion;
item.HttpKeepAliveInterval = HttpKeepAliveInterval; item.HttpKeepAliveInterval = HttpKeepAliveInterval;
#if NET5_0_OR_GREATER
item.HttpMaxConnectionsPerServer = HttpMaxConnectionsPerServer;
item.HttpPooledConnectionLifetime = HttpPooledConnectionLifetime;
item.HttpPooledConnectionIdleTimeout = HttpPooledConnectionIdleTimeout;
item.HttpEnableMultipleHttp2Connections = HttpEnableMultipleHttp2Connections;
#endif
return item; return item;
} }
} }

View File

@ -12,14 +12,16 @@ namespace CryptoExchange.Net.Requests
public class RequestFactory : IRequestFactory public class RequestFactory : IRequestFactory
{ {
private HttpClient? _httpClient; private HttpClient? _httpClient;
private RestExchangeOptions? _options;
/// <inheritdoc /> /// <inheritdoc />
public void Configure(RestExchangeOptions options, HttpClient? client = null) public void Configure(RestExchangeOptions options, HttpClient? client = null)
{ {
if (client == null) if (client == null)
client = CreateClient(options.Proxy, options.RequestTimeout, options.HttpKeepAliveInterval); client = CreateClient(options);
_httpClient = client; _httpClient = client;
_options = options;
} }
/// <inheritdoc /> /// <inheritdoc />
@ -39,15 +41,20 @@ namespace CryptoExchange.Net.Requests
/// <inheritdoc /> /// <inheritdoc />
public void UpdateSettings(ApiProxy? proxy, TimeSpan requestTimeout, TimeSpan? httpKeepAliveInterval) public void UpdateSettings(ApiProxy? proxy, TimeSpan requestTimeout, TimeSpan? httpKeepAliveInterval)
{ {
_httpClient = CreateClient(proxy, requestTimeout, httpKeepAliveInterval); var newOptions = new RestExchangeOptions();
_options!.Set(newOptions);
newOptions.Proxy = proxy;
newOptions.RequestTimeout = requestTimeout;
newOptions.HttpKeepAliveInterval = httpKeepAliveInterval;
_httpClient = CreateClient(newOptions);
} }
private static HttpClient CreateClient(ApiProxy? proxy, TimeSpan requestTimeout, TimeSpan? httpKeepAliveInterval) private static HttpClient CreateClient(RestExchangeOptions options)
{ {
var handler = LibraryHelpers.CreateHttpClientMessageHandler(proxy, httpKeepAliveInterval); var handler = LibraryHelpers.CreateHttpClientMessageHandler(options);
var client = new HttpClient(handler) var client = new HttpClient(handler)
{ {
Timeout = requestTimeout Timeout = options.RequestTimeout
}; };
return client; return client;
} }

View File

@ -123,8 +123,15 @@ namespace CryptoExchange.Net.Sockets.Default
{ {
get get
{ {
lock (_listenersLock) _listenersLock.EnterReadLock();
try
{
return _listeners.OfType<Subscription>().Count(h => h.UserSubscription); return _listeners.OfType<Subscription>().Count(h => h.UserSubscription);
}
finally
{
_listenersLock.ExitReadLock();
}
} }
} }
@ -135,8 +142,16 @@ namespace CryptoExchange.Net.Sockets.Default
{ {
get get
{ {
lock (_listenersLock) _listenersLock.EnterReadLock();
try
{
return _listeners.OfType<Subscription>().Where(h => h.UserSubscription).ToArray(); return _listeners.OfType<Subscription>().Where(h => h.UserSubscription).ToArray();
}
finally
{
_listenersLock.ExitReadLock();
}
} }
} }
@ -240,8 +255,15 @@ namespace CryptoExchange.Net.Sockets.Default
{ {
get get
{ {
lock (_listenersLock) _listenersLock.EnterReadLock();
try
{
return _listeners.OfType<Subscription>().Select(x => x.Topic).Where(t => t != null).ToArray()!; return _listeners.OfType<Subscription>().Select(x => x.Topic).Where(t => t != null).ToArray()!;
}
finally
{
_listenersLock.ExitReadLock();
}
} }
} }
@ -252,18 +274,21 @@ namespace CryptoExchange.Net.Sockets.Default
{ {
get get
{ {
lock (_listenersLock) _listenersLock.EnterReadLock();
try
{
return _listeners.OfType<Query>().Where(x => !x.Completed).Count(); return _listeners.OfType<Query>().Where(x => !x.Completed).Count();
}
finally
{
_listenersLock.ExitReadLock();
}
} }
} }
private bool _pausedActivity; private bool _pausedActivity;
#if NET9_0_OR_GREATER private readonly ReaderWriterLockSlim _listenersLock = new ReaderWriterLockSlim();
private readonly Lock _listenersLock = new Lock();
#else
private readonly object _listenersLock = new object();
#endif
private readonly List<IMessageProcessor> _listeners; private readonly List<IMessageProcessor> _listeners;
private readonly ILogger _logger; private readonly ILogger _logger;
private SocketStatus _status; private SocketStatus _status;
@ -340,7 +365,8 @@ namespace CryptoExchange.Net.Sockets.Default
if (ApiClient._socketConnections.ContainsKey(SocketId)) if (ApiClient._socketConnections.ContainsKey(SocketId))
ApiClient._socketConnections.TryRemove(SocketId, out _); ApiClient._socketConnections.TryRemove(SocketId, out _);
lock (_listenersLock) _listenersLock.EnterWriteLock();
try
{ {
foreach (var subscription in _listeners.OfType<Subscription>().Where(l => l.UserSubscription && !l.IsClosingConnection)) foreach (var subscription in _listeners.OfType<Subscription>().Where(l => l.UserSubscription && !l.IsClosingConnection))
{ {
@ -354,6 +380,10 @@ namespace CryptoExchange.Net.Sockets.Default
_listeners.Remove(query); _listeners.Remove(query);
} }
} }
finally
{
_listenersLock.ExitWriteLock();
}
_ = Task.Run(() => ConnectionClosed?.Invoke()); _ = Task.Run(() => ConnectionClosed?.Invoke());
return Task.CompletedTask; return Task.CompletedTask;
@ -369,7 +399,8 @@ namespace CryptoExchange.Net.Sockets.Default
Authenticated = false; Authenticated = false;
_lastSequenceNumber = 0; _lastSequenceNumber = 0;
lock (_listenersLock) _listenersLock.EnterWriteLock();
try
{ {
foreach (var subscription in _listeners.OfType<Subscription>().Where(l => l.UserSubscription)) foreach (var subscription in _listeners.OfType<Subscription>().Where(l => l.UserSubscription))
subscription.Reset(); subscription.Reset();
@ -380,6 +411,10 @@ namespace CryptoExchange.Net.Sockets.Default
_listeners.Remove(query); _listeners.Remove(query);
} }
} }
finally
{
_listenersLock.ExitWriteLock();
}
_ = Task.Run(() => ConnectionLost?.Invoke()); _ = Task.Run(() => ConnectionLost?.Invoke());
return Task.CompletedTask; return Task.CompletedTask;
@ -401,7 +436,8 @@ namespace CryptoExchange.Net.Sockets.Default
{ {
Status = SocketStatus.Resubscribing; Status = SocketStatus.Resubscribing;
lock (_listenersLock) _listenersLock.EnterWriteLock();
try
{ {
foreach (var query in _listeners.OfType<Query>().ToList()) foreach (var query in _listeners.OfType<Query>().ToList())
{ {
@ -409,6 +445,10 @@ namespace CryptoExchange.Net.Sockets.Default
_listeners.Remove(query); _listeners.Remove(query);
} }
} }
finally
{
_listenersLock.ExitWriteLock();
}
// Can't wait for this as it would cause a deadlock // Can't wait for this as it would cause a deadlock
_ = Task.Run(async () => _ = Task.Run(async () =>
@ -464,10 +504,15 @@ namespace CryptoExchange.Net.Sockets.Default
protected virtual Task HandleRequestRateLimitedAsync(int requestId) protected virtual Task HandleRequestRateLimitedAsync(int requestId)
{ {
Query? query; Query? query;
lock (_listenersLock) _listenersLock.EnterReadLock();
try
{ {
query = _listeners.OfType<Query>().FirstOrDefault(x => x.Id == requestId); query = _listeners.OfType<Query>().FirstOrDefault(x => x.Id == requestId);
} }
finally
{
_listenersLock.ExitReadLock();
}
if (query == null) if (query == null)
return Task.CompletedTask; return Task.CompletedTask;
@ -493,10 +538,15 @@ namespace CryptoExchange.Net.Sockets.Default
protected virtual Task HandleRequestSentAsync(int requestId) protected virtual Task HandleRequestSentAsync(int requestId)
{ {
Query? query; Query? query;
lock (_listenersLock) _listenersLock.EnterReadLock();
try
{ {
query = _listeners.OfType<Query>().FirstOrDefault(x => x.Id == requestId); query = _listeners.OfType<Query>().FirstOrDefault(x => x.Id == requestId);
} }
finally
{
_listenersLock.ExitReadLock();
}
if (query == null) if (query == null)
return Task.CompletedTask; return Task.CompletedTask;
@ -543,7 +593,8 @@ namespace CryptoExchange.Net.Sockets.Default
} }
Type? deserializationType = null; Type? deserializationType = null;
lock (_listenersLock) _listenersLock.EnterReadLock();
try
{ {
foreach (var subscription in _listeners) foreach (var subscription in _listeners)
{ {
@ -560,6 +611,10 @@ namespace CryptoExchange.Net.Sockets.Default
break; break;
} }
} }
finally
{
_listenersLock.ExitReadLock();
}
if (deserializationType == null) if (deserializationType == null)
{ {
@ -605,7 +660,8 @@ namespace CryptoExchange.Net.Sockets.Default
var topicFilter = messageConverter.GetTopicFilter(result); var topicFilter = messageConverter.GetTopicFilter(result);
bool processed = false; bool processed = false;
lock (_listenersLock) _listenersLock.EnterReadLock();
try
{ {
var currentCount = _listeners.Count; var currentCount = _listeners.Count;
for(var i = 0; i < _listeners.Count; i++) for(var i = 0; i < _listeners.Count; i++)
@ -670,12 +726,17 @@ namespace CryptoExchange.Net.Sockets.Default
break; break;
} }
} }
finally
{
_listenersLock.ExitReadLock();
}
if (!processed) if (!processed)
{ {
if (!ApiClient.HandleUnhandledMessage(this, typeIdentifier, data)) if (!ApiClient.HandleUnhandledMessage(this, typeIdentifier, data))
{ {
lock (_listenersLock) _listenersLock.EnterReadLock();
try
{ {
_logger.ReceivedMessageNotMatchedToAnyListener( _logger.ReceivedMessageNotMatchedToAnyListener(
SocketId, SocketId,
@ -683,6 +744,10 @@ namespace CryptoExchange.Net.Sockets.Default
topicFilter!, topicFilter!,
string.Join(",", _listeners.Select(x => string.Join(",", x.MessageRouter.Routes.Where(x => x.TypeIdentifier == typeIdentifier).Select(x => x.TopicFilter != null ? string.Join(",", x.TopicFilter) : "[null]"))))); string.Join(",", _listeners.Select(x => string.Join(",", x.MessageRouter.Routes.Where(x => x.TypeIdentifier == typeIdentifier).Select(x => x.TopicFilter != null ? string.Join(",", x.TopicFilter) : "[null]")))));
} }
finally
{
_listenersLock.ExitReadLock();
}
} }
} }
} }
@ -727,7 +792,8 @@ namespace CryptoExchange.Net.Sockets.Default
if (ApiClient._socketConnections.ContainsKey(SocketId)) if (ApiClient._socketConnections.ContainsKey(SocketId))
ApiClient._socketConnections.TryRemove(SocketId, out _); ApiClient._socketConnections.TryRemove(SocketId, out _);
lock (_listenersLock) _listenersLock.EnterReadLock();
try
{ {
foreach (var subscription in _listeners.OfType<Subscription>()) foreach (var subscription in _listeners.OfType<Subscription>())
{ {
@ -735,6 +801,10 @@ namespace CryptoExchange.Net.Sockets.Default
subscription.CancellationTokenRegistration.Value.Dispose(); subscription.CancellationTokenRegistration.Value.Dispose();
} }
} }
finally
{
_listenersLock.ExitReadLock();
}
await _socket.CloseAsync().ConfigureAwait(false); await _socket.CloseAsync().ConfigureAwait(false);
_socket.Dispose(); _socket.Dispose();
@ -764,18 +834,30 @@ namespace CryptoExchange.Net.Sockets.Default
subscription.CancellationTokenRegistration.Value.Dispose(); subscription.CancellationTokenRegistration.Value.Dispose();
bool anyDuplicateSubscription; bool anyDuplicateSubscription;
lock (_listenersLock)
anyDuplicateSubscription = _listeners.OfType<Subscription>().Any(x => x != subscription && x.MessageRouter.Routes.All(l => subscription.MessageRouter.ContainsCheck(l)));
bool shouldCloseConnection; bool shouldCloseConnection;
lock (_listenersLock) _listenersLock.EnterReadLock();
try
{
anyDuplicateSubscription = _listeners.OfType<Subscription>().Any(x => x != subscription && x.MessageRouter.Routes.All(l => subscription.MessageRouter.ContainsCheck(l)));
shouldCloseConnection = _listeners.OfType<Subscription>().All(r => !r.UserSubscription || r.Status == SubscriptionStatus.Closing || r.Status == SubscriptionStatus.Closed) && !DedicatedRequestConnection.IsDedicatedRequestConnection; shouldCloseConnection = _listeners.OfType<Subscription>().All(r => !r.UserSubscription || r.Status == SubscriptionStatus.Closing || r.Status == SubscriptionStatus.Closed) && !DedicatedRequestConnection.IsDedicatedRequestConnection;
}
finally
{
_listenersLock.ExitReadLock();
}
if (!anyDuplicateSubscription) if (!anyDuplicateSubscription)
{ {
bool needUnsub; bool needUnsub;
lock (_listenersLock) _listenersLock.EnterReadLock();
try
{
needUnsub = _listeners.Contains(subscription) && !shouldCloseConnection; needUnsub = _listeners.Contains(subscription) && !shouldCloseConnection;
}
finally
{
_listenersLock.ExitReadLock();
}
if (needUnsub && _socket.IsOpen) if (needUnsub && _socket.IsOpen)
await UnsubscribeAsync(subscription).ConfigureAwait(false); await UnsubscribeAsync(subscription).ConfigureAwait(false);
@ -800,8 +882,15 @@ namespace CryptoExchange.Net.Sockets.Default
await CloseAsync().ConfigureAwait(false); await CloseAsync().ConfigureAwait(false);
} }
lock (_listenersLock) _listenersLock.EnterWriteLock();
try
{
_listeners.Remove(subscription); _listeners.Remove(subscription);
}
finally
{
_listenersLock.ExitWriteLock();
}
subscription.Status = SubscriptionStatus.Closed; subscription.Status = SubscriptionStatus.Closed;
} }
@ -825,8 +914,15 @@ namespace CryptoExchange.Net.Sockets.Default
if (Status != SocketStatus.None && Status != SocketStatus.Connected) if (Status != SocketStatus.None && Status != SocketStatus.Connected)
return false; return false;
lock (_listenersLock) _listenersLock.EnterWriteLock();
try
{
_listeners.Add(subscription); _listeners.Add(subscription);
}
finally
{
_listenersLock.ExitWriteLock();
}
if (subscription.UserSubscription) if (subscription.UserSubscription)
_logger.AddingNewSubscription(SocketId, subscription.Id, UserSubscriptionCount); _logger.AddingNewSubscription(SocketId, subscription.Id, UserSubscriptionCount);
@ -839,8 +935,15 @@ namespace CryptoExchange.Net.Sockets.Default
/// <param name="id"></param> /// <param name="id"></param>
public Subscription? GetSubscription(int id) public Subscription? GetSubscription(int id)
{ {
lock (_listenersLock) _listenersLock.EnterReadLock();
try
{
return _listeners.OfType<Subscription>().SingleOrDefault(s => s.Id == id); return _listeners.OfType<Subscription>().SingleOrDefault(s => s.Id == id);
}
finally
{
_listenersLock.ExitReadLock();
}
} }
/// <summary> /// <summary>
@ -888,15 +991,29 @@ namespace CryptoExchange.Net.Sockets.Default
private async Task SendAndWaitIntAsync(Query query, CancellationToken ct = default) private async Task SendAndWaitIntAsync(Query query, CancellationToken ct = default)
{ {
lock (_listenersLock) _listenersLock.EnterWriteLock();
try
{
_listeners.Add(query); _listeners.Add(query);
}
finally
{
_listenersLock.ExitWriteLock();
}
var sendResult = await SendAsync(query.Id, query.Request, query.Weight).ConfigureAwait(false); var sendResult = await SendAsync(query.Id, query.Request, query.Weight).ConfigureAwait(false);
if (!sendResult) if (!sendResult)
{ {
query.Fail(sendResult.Error!); query.Fail(sendResult.Error!);
lock (_listenersLock) _listenersLock.EnterWriteLock();
try
{
_listeners.Remove(query); _listeners.Remove(query);
}
finally
{
_listenersLock.ExitWriteLock();
}
return; return;
} }
@ -927,8 +1044,15 @@ namespace CryptoExchange.Net.Sockets.Default
} }
finally finally
{ {
lock (_listenersLock) _listenersLock.EnterWriteLock();
try
{
_listeners.Remove(query); _listeners.Remove(query);
}
finally
{
_listenersLock.ExitWriteLock();
}
} }
} }
@ -1035,8 +1159,16 @@ namespace CryptoExchange.Net.Sockets.Default
if (!DedicatedRequestConnection.IsDedicatedRequestConnection) if (!DedicatedRequestConnection.IsDedicatedRequestConnection)
{ {
bool anySubscriptions; bool anySubscriptions;
lock (_listenersLock) _listenersLock.EnterReadLock();
try
{
anySubscriptions = _listeners.OfType<Subscription>().Any(s => s.UserSubscription); anySubscriptions = _listeners.OfType<Subscription>().Any(s => s.UserSubscription);
}
finally
{
_listenersLock.ExitReadLock();
}
if (!anySubscriptions) if (!anySubscriptions)
{ {
// No need to resubscribe anything // No need to resubscribe anything
@ -1047,11 +1179,16 @@ namespace CryptoExchange.Net.Sockets.Default
} }
bool anyAuthenticated; bool anyAuthenticated;
lock (_listenersLock) _listenersLock.EnterReadLock();
try
{ {
anyAuthenticated = _listeners.OfType<Subscription>().Any(s => s.Authenticated) anyAuthenticated = _listeners.OfType<Subscription>().Any(s => s.Authenticated)
|| DedicatedRequestConnection.IsDedicatedRequestConnection && DedicatedRequestConnection.Authenticated; || DedicatedRequestConnection.IsDedicatedRequestConnection && DedicatedRequestConnection.Authenticated;
} }
finally
{
_listenersLock.ExitReadLock();
}
if (anyAuthenticated) if (anyAuthenticated)
{ {
@ -1076,8 +1213,15 @@ namespace CryptoExchange.Net.Sockets.Default
return new CallResult(new WebError("Socket not connected")); return new CallResult(new WebError("Socket not connected"));
List<Subscription> subList; List<Subscription> subList;
lock (_listenersLock) _listenersLock.EnterReadLock();
try
{
subList = _listeners.OfType<Subscription>().Where(x => x.Active).Skip(batch * batchSize).Take(batchSize).ToList(); subList = _listeners.OfType<Subscription>().Where(x => x.Active).Skip(batch * batchSize).Take(batchSize).ToList();
}
finally
{
_listenersLock.ExitReadLock();
}
if (subList.Count == 0) if (subList.Count == 0)
break; break;

View File

@ -112,6 +112,8 @@ namespace CryptoExchange.Net.Testing.Implementations
public async Task ReconnectAsync() public async Task ReconnectAsync()
{ {
await Task.Delay(1).ConfigureAwait(false);
if (OnReconnecting != null) if (OnReconnecting != null)
await OnReconnecting().ConfigureAwait(false); await OnReconnecting().ConfigureAwait(false);

View File

@ -67,6 +67,24 @@ Make a one time donation in a crypto currency of your choice. If you prefer to d
Alternatively, sponsor me on Github using [Github Sponsors](https://github.com/sponsors/JKorf). Alternatively, sponsor me on Github using [Github Sponsors](https://github.com/sponsors/JKorf).
## Release notes ## Release notes
* Version 10.7.0 - 24 Feb 2026
* Added parsing of REST response data up to 128 characters for error responses
* Added check for invalid json in JsonSocketMessageHandler
* Added virtual GetTypeIdentifierNonJson for handling non-json messages in JsonSocketMessageHandler
* Added additional options to Rest client options for configuring HttpClient
* Updated INextPageToken parameter on Shared interfaces to PageRequest type, functionality unchanged
* Added SupportsAscending and SupportsDescending properties to PaginatedEndpointOptions to expose supported data directions
* Added MaxAge property to PaginatedEndpointOptions to expose the max age of data that can be requested
* Added Direction property to Shared interfaces paginated requests to configure pagination data direction
* Removed PaginationSupport property from PaginatedEndpointOptions, replaced by above new properties
* Updated Shared GetTradeHistoryRequest EndTime property to be optional
* Updated I(Futures/Spot)OrderRestClient.GetClosed(Futures/Spot)OrdersOptions from PaginatedEndpointOptions<GetClosedOrdersRequest> to GetClosedOrdersOptions
* Updated I(Futures/Spot)OrderRestClient.Get(Futures/Spot)UserTradesOptions from PaginatedEndpointOptions<GetUserTradesRequest> to GetUserTradesOptions
* Updated rate limiting PathStartFilter to ignore added or missing slash before the path
* Updated internal lock for subscription to ReaderWriterLockSlim on SocketConnection
* Removed check for OnlyTrackProvidedSymbols in combination with empty TrackedSymbols list
* Fixed KlineTracker throwing exception if there is no data in the initial snapshot
* Version 10.6.2 - 17 Feb 2026 * Version 10.6.2 - 17 Feb 2026
* Fix for websocket queries which don't expects response getting stuck in subscribing state * Fix for websocket queries which don't expects response getting stuck in subscribing state