public async Task SubscribeAsync(IBinanceApiUser user, Action <UserDataEventArgs> callback, CancellationToken token = default) { Throw.IfNull(user, nameof(user)); if (_listenKeys.ContainsKey(user)) { throw new InvalidOperationException($"{nameof(UserDataWebSocketClient)}: Already subscribed to user."); } try { _listenKeys[user] = await _api.UserStreamStartAsync(user, token) .ConfigureAwait(false); if (string.IsNullOrWhiteSpace(_listenKeys[user])) { throw new Exception($"{nameof(IUserDataWebSocketClient)}: Failed to get listen key from API."); } SubscribeTo(_listenKeys[user], callback); } catch (OperationCanceledException) { } catch (Exception e) { if (!token.IsCancellationRequested) { Logger?.LogError(e, $"{nameof(UserDataWebSocketClient)}.{nameof(SubscribeAsync)}"); throw; } } }
public virtual async Task SubscribeAsync(IBinanceApiUser user, Action <UserDataEventArgs> callback, CancellationToken token) { Throw.IfNull(user, nameof(user)); if (!token.CanBeCanceled) { throw new ArgumentException("Token must be capable of being in the canceled state.", nameof(token)); } token.ThrowIfCancellationRequested(); User = user; if (IsSubscribed) { throw new InvalidOperationException($"{nameof(UserDataWebSocketClient)} is already subscribed to a user."); } try { _listenKey = await _api.UserStreamStartAsync(user, token) .ConfigureAwait(false); if (string.IsNullOrWhiteSpace(_listenKey)) { throw new Exception($"{nameof(IUserDataWebSocketClient)}: Failed to get listen key from API."); } var period = _options?.KeepAliveTimerPeriod ?? KeepAliveTimerPeriodDefault; period = Math.Min(Math.Max(period, KeepAliveTimerPeriodMin), KeepAliveTimerPeriodMax); _keepAliveTimer = new Timer(OnKeepAliveTimer, token, period, period); try { await SubscribeToAsync(_listenKey, callback, token) .ConfigureAwait(false); } finally { _keepAliveTimer.Dispose(); await _api.UserStreamCloseAsync(User, _listenKey, CancellationToken.None) .ConfigureAwait(false); } } catch (OperationCanceledException) { } catch (Exception e) { if (!token.IsCancellationRequested) { Logger?.LogError(e, $"{nameof(UserDataWebSocketClient)}.{nameof(SubscribeAsync)}"); throw; } } }