Add various optimizations and cleanups (#1114)

* Change all Select(... as ...) to OfType

* Add changes according to 194a8aa427
This commit is contained in:
Still Hsu
2018-08-31 05:36:44 +08:00
committed by Christopher F
parent a2d8800115
commit 82cfdffc65
46 changed files with 131 additions and 135 deletions

View File

@@ -16,7 +16,7 @@ using System.Collections.Generic;
namespace Discord.Audio
{
//TODO: Add audio reconnecting
internal partial class AudioClient : IAudioClient, IDisposable
internal partial class AudioClient : IAudioClient
{
internal struct StreamPair
{
@@ -65,7 +65,7 @@ namespace Discord.Audio
ApiClient = new DiscordVoiceAPIClient(guild.Id, Discord.WebSocketProvider, Discord.UdpSocketProvider);
ApiClient.SentGatewayMessage += async opCode => await _audioLogger.DebugAsync($"Sent {opCode}").ConfigureAwait(false);
ApiClient.SentDiscovery += async () => await _audioLogger.DebugAsync($"Sent Discovery").ConfigureAwait(false);
ApiClient.SentDiscovery += async () => await _audioLogger.DebugAsync("Sent Discovery").ConfigureAwait(false);
//ApiClient.SentData += async bytes => await _audioLogger.DebugAsync($"Sent {bytes} Bytes").ConfigureAwait(false);
ApiClient.ReceivedEvent += ProcessMessageAsync;
ApiClient.ReceivedPacket += ProcessPacketAsync;
@@ -131,7 +131,7 @@ namespace Discord.Audio
await keepaliveTask.ConfigureAwait(false);
_keepaliveTask = null;
while (_heartbeatTimes.TryDequeue(out long time)) { }
while (_heartbeatTimes.TryDequeue(out _)) { }
_lastMessageTime = 0;
await ClearInputStreamsAsync().ConfigureAwait(false);
@@ -292,7 +292,7 @@ namespace Discord.Audio
{
if (packet.Length != 70)
{
await _audioLogger.DebugAsync($"Malformed Packet").ConfigureAwait(false);
await _audioLogger.DebugAsync("Malformed Packet").ConfigureAwait(false);
return;
}
string ip;
@@ -304,7 +304,7 @@ namespace Discord.Audio
}
catch (Exception ex)
{
await _audioLogger.DebugAsync($"Malformed Packet", ex).ConfigureAwait(false);
await _audioLogger.DebugAsync("Malformed Packet", ex).ConfigureAwait(false);
return;
}
@@ -331,7 +331,7 @@ namespace Discord.Audio
{
if (pair.Key == value)
{
int latency = (int)(Environment.TickCount - pair.Value);
int latency = Environment.TickCount - pair.Value;
int before = UdpLatency;
UdpLatency = latency;
@@ -344,7 +344,7 @@ namespace Discord.Audio
{
if (!RTPReadStream.TryReadSsrc(packet, 0, out var ssrc))
{
await _audioLogger.DebugAsync($"Malformed Frame").ConfigureAwait(false);
await _audioLogger.DebugAsync("Malformed Frame").ConfigureAwait(false);
return;
}
if (!_ssrcMap.TryGetValue(ssrc, out var userId))
@@ -363,7 +363,7 @@ namespace Discord.Audio
}
catch (Exception ex)
{
await _audioLogger.DebugAsync($"Malformed Frame", ex).ConfigureAwait(false);
await _audioLogger.DebugAsync("Malformed Frame", ex).ConfigureAwait(false);
return;
}
//await _audioLogger.DebugAsync($"Received {packet.Length} bytes from user {userId}").ConfigureAwait(false);
@@ -372,7 +372,7 @@ namespace Discord.Audio
}
catch (Exception ex)
{
await _audioLogger.WarningAsync($"Failed to process UDP packet", ex).ConfigureAwait(false);
await _audioLogger.WarningAsync("Failed to process UDP packet", ex).ConfigureAwait(false);
return;
}
}

View File

@@ -116,7 +116,7 @@ namespace Discord.Audio.Streams
timestamp += OpusEncoder.FrameSamplesPerChannel;
}
#if DEBUG
var _ = _logger?.DebugAsync($"Buffer underrun");
var _ = _logger?.DebugAsync("Buffer underrun");
#endif
}
}
@@ -140,7 +140,7 @@ namespace Discord.Audio.Streams
if (!_bufferPool.TryDequeue(out byte[] buffer))
{
#if DEBUG
var _ = _logger?.DebugAsync($"Buffer overflow"); //Should never happen because of the queueLock
var _ = _logger?.DebugAsync("Buffer overflow"); //Should never happen because of the queueLock
#endif
return;
}
@@ -149,7 +149,7 @@ namespace Discord.Audio.Streams
if (!_isPreloaded && _queuedFrames.Count == _queueLength)
{
#if DEBUG
var _ = _logger?.DebugAsync($"Preloaded");
var _ = _logger?.DebugAsync("Preloaded");
#endif
_isPreloaded = true;
}
@@ -169,8 +169,8 @@ namespace Discord.Audio.Streams
{
do
cancelToken.ThrowIfCancellationRequested();
while (_queuedFrames.TryDequeue(out Frame ignored));
while (_queuedFrames.TryDequeue(out _));
return Task.Delay(0);
}
}
}
}

View File

@@ -1,4 +1,4 @@
using System;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
@@ -72,7 +72,7 @@ namespace Discord.WebSocket
switch (channel)
{
case SocketDMChannel dmChannel:
_dmChannels.TryRemove(dmChannel.Recipient.Id, out var ignored);
_dmChannels.TryRemove(dmChannel.Recipient.Id, out _);
break;
case SocketGroupChannel groupChannel:
_groupChannels.TryRemove(id);

View File

@@ -13,11 +13,11 @@ namespace Discord.WebSocket
{
private readonly DiscordSocketConfig _baseConfig;
private readonly SemaphoreSlim _connectionGroupLock;
private readonly Dictionary<int, int> _shardIdsToIndex;
private readonly bool _automaticShards;
private int[] _shardIds;
private Dictionary<int, int> _shardIdsToIndex;
private DiscordSocketClient[] _shards;
private int _totalShards;
private bool _automaticShards;
/// <summary> Gets the estimated round-trip latency, in milliseconds, to the gateway server. </summary>
public override int Latency { get => GetLatency(); protected set { } }
@@ -25,8 +25,8 @@ namespace Discord.WebSocket
public override IActivity Activity { get => _shards[0].Activity; protected set { } }
internal new DiscordSocketApiClient ApiClient => base.ApiClient as DiscordSocketApiClient;
public override IReadOnlyCollection<SocketGuild> Guilds => GetGuilds().ToReadOnlyCollection(() => GetGuildCount());
public override IReadOnlyCollection<ISocketPrivateChannel> PrivateChannels => GetPrivateChannels().ToReadOnlyCollection(() => GetPrivateChannelCount());
public override IReadOnlyCollection<SocketGuild> Guilds => GetGuilds().ToReadOnlyCollection(GetGuildCount);
public override IReadOnlyCollection<ISocketPrivateChannel> PrivateChannels => GetPrivateChannels().ToReadOnlyCollection(GetPrivateChannelCount);
public IReadOnlyCollection<DiscordSocketClient> Shards => _shards;
public override IReadOnlyCollection<RestVoiceRegion> VoiceRegions => _shards[0].VoiceRegions;

View File

@@ -26,9 +26,9 @@ namespace Discord.API
public event Func<Exception, Task> Disconnected { add { _disconnectedEvent.Add(value); } remove { _disconnectedEvent.Remove(value); } }
private readonly AsyncEvent<Func<Exception, Task>> _disconnectedEvent = new AsyncEvent<Func<Exception, Task>>();
private readonly bool _isExplicitUrl;
private CancellationTokenSource _connectCancelToken;
private string _gatewayUrl;
private bool _isExplicitUrl;
//Store our decompression streams for zlib shared state
private MemoryStream _compressed;

View File

@@ -63,9 +63,9 @@ namespace Discord.WebSocket
public override IReadOnlyCollection<SocketGuild> Guilds => State.Guilds;
public override IReadOnlyCollection<ISocketPrivateChannel> PrivateChannels => State.PrivateChannels;
public IReadOnlyCollection<SocketDMChannel> DMChannels
=> State.PrivateChannels.Select(x => x as SocketDMChannel).Where(x => x != null).ToImmutableArray();
=> State.PrivateChannels.OfType<SocketDMChannel>().ToImmutableArray();
public IReadOnlyCollection<SocketGroupChannel> GroupChannels
=> State.PrivateChannels.Select(x => x as SocketGroupChannel).Where(x => x != null).ToImmutableArray();
=> State.PrivateChannels.OfType<SocketGroupChannel>().ToImmutableArray();
public override IReadOnlyCollection<RestVoiceRegion> VoiceRegions => _voiceRegions.ToReadOnlyCollection();
/// <summary> Creates a new REST/WebSocket discord client. </summary>
@@ -207,7 +207,7 @@ namespace Discord.WebSocket
await heartbeatTask.ConfigureAwait(false);
_heartbeatTask = null;
while (_heartbeatTimes.TryDequeue(out long time)) { }
while (_heartbeatTimes.TryDequeue(out _)) { }
_lastMessageTime = 0;
await _gatewayLogger.DebugAsync("Waiting for guild downloader").ConfigureAwait(false);
@@ -218,7 +218,7 @@ namespace Discord.WebSocket
//Clear large guild queue
await _gatewayLogger.DebugAsync("Clearing large guild queue").ConfigureAwait(false);
while (_largeGuilds.TryDequeue(out ulong guildId)) { }
while (_largeGuilds.TryDequeue(out _)) { }
//Raise virtual GUILD_UNAVAILABLEs
await _gatewayLogger.DebugAsync("Raising virtual GuildUnavailables").ConfigureAwait(false);
@@ -351,7 +351,7 @@ namespace Discord.WebSocket
var gameModel = new GameModel();
// Discord only accepts rich presence over RPC, don't even bother building a payload
if (Activity is RichGame game)
if (Activity is RichGame)
throw new NotSupportedException("Outgoing Rich Presences are not supported");
if (Activity != null)
@@ -508,7 +508,7 @@ namespace Discord.WebSocket
{
type = "GUILD_AVAILABLE";
_lastGuildAvailableTime = Environment.TickCount;
await _gatewayLogger.DebugAsync($"Received Dispatch (GUILD_AVAILABLE)").ConfigureAwait(false);
await _gatewayLogger.DebugAsync("Received Dispatch (GUILD_AVAILABLE)").ConfigureAwait(false);
var guild = State.GetGuild(data.Id);
if (guild != null)
@@ -533,7 +533,7 @@ namespace Discord.WebSocket
}
else
{
await _gatewayLogger.DebugAsync($"Received Dispatch (GUILD_CREATE)").ConfigureAwait(false);
await _gatewayLogger.DebugAsync("Received Dispatch (GUILD_CREATE)").ConfigureAwait(false);
var guild = AddGuild(data, State);
if (guild != null)
@@ -614,7 +614,7 @@ namespace Discord.WebSocket
if (data.Unavailable == true)
{
type = "GUILD_UNAVAILABLE";
await _gatewayLogger.DebugAsync($"Received Dispatch (GUILD_UNAVAILABLE)").ConfigureAwait(false);
await _gatewayLogger.DebugAsync("Received Dispatch (GUILD_UNAVAILABLE)").ConfigureAwait(false);
var guild = State.GetGuild(data.Id);
if (guild != null)
@@ -630,7 +630,7 @@ namespace Discord.WebSocket
}
else
{
await _gatewayLogger.DebugAsync($"Received Dispatch (GUILD_DELETE)").ConfigureAwait(false);
await _gatewayLogger.DebugAsync("Received Dispatch (GUILD_DELETE)").ConfigureAwait(false);
var guild = RemoveGuild(data.Id);
if (guild != null)
@@ -1626,7 +1626,7 @@ namespace Discord.WebSocket
var guild = State.RemoveGuild(id);
if (guild != null)
{
foreach (var channel in guild.Channels)
foreach (var _ in guild.Channels)
State.RemoveChannel(id);
foreach (var user in guild.Users)
user.GlobalUser.RemoveRef(this);
@@ -1679,7 +1679,7 @@ namespace Discord.WebSocket
if (eventHandler.HasSubscribers)
{
if (HandlerTimeout.HasValue)
await TimeoutWrap(name, () => eventHandler.InvokeAsync()).ConfigureAwait(false);
await TimeoutWrap(name, eventHandler.InvokeAsync).ConfigureAwait(false);
else
await eventHandler.InvokeAsync().ConfigureAwait(false);
}

View File

@@ -39,8 +39,8 @@ namespace Discord.Audio
private readonly JsonSerializer _serializer;
private readonly SemaphoreSlim _connectionLock;
private readonly IUdpSocket _udp;
private CancellationTokenSource _connectCancelToken;
private IUdpSocket _udp;
private bool _isDisposed;
private ulong _nextKeepalive;
@@ -188,7 +188,7 @@ namespace Discord.Audio
ConnectionState = ConnectionState.Connected;
}
catch (Exception)
catch
{
await DisconnectInternalAsync().ConfigureAwait(false);
throw;

View File

@@ -97,7 +97,7 @@ namespace Discord.WebSocket
if (id == Recipient.Id)
return Recipient;
else if (id == Discord.CurrentUser.Id)
return Discord.CurrentUser as SocketSelfUser;
return Discord.CurrentUser;
else
return null;
}

View File

@@ -18,10 +18,10 @@ namespace Discord.WebSocket
public class SocketGroupChannel : SocketChannel, IGroupChannel, ISocketPrivateChannel, ISocketMessageChannel, ISocketAudioChannel
{
private readonly MessageCache _messages;
private readonly ConcurrentDictionary<ulong, SocketVoiceState> _voiceStates;
private string _iconId;
private ConcurrentDictionary<ulong, SocketGroupUser> _users;
private ConcurrentDictionary<ulong, SocketVoiceState> _voiceStates;
public string Name { get; private set; }
@@ -129,7 +129,7 @@ namespace Discord.WebSocket
internal SocketGroupUser GetOrAddUser(UserModel model)
{
if (_users.TryGetValue(model.Id, out SocketGroupUser user))
return user as SocketGroupUser;
return user;
else
{
var privateUser = SocketGroupUser.Create(this, Discord.State, model);
@@ -143,7 +143,7 @@ namespace Discord.WebSocket
if (_users.TryRemove(id, out SocketGroupUser user))
{
user.GlobalUser.RemoveRef(Discord);
return user as SocketGroupUser;
return user;
}
return null;
}

View File

@@ -91,11 +91,11 @@ namespace Discord.WebSocket
}
}
public IReadOnlyCollection<SocketTextChannel> TextChannels
=> Channels.Select(x => x as SocketTextChannel).Where(x => x != null).ToImmutableArray();
=> Channels.OfType<SocketTextChannel>().ToImmutableArray();
public IReadOnlyCollection<SocketVoiceChannel> VoiceChannels
=> Channels.Select(x => x as SocketVoiceChannel).Where(x => x != null).ToImmutableArray();
=> Channels.OfType<SocketVoiceChannel>().ToImmutableArray();
public IReadOnlyCollection<SocketCategoryChannel> CategoryChannels
=> Channels.Select(x => x as SocketCategoryChannel).Where(x => x != null).ToImmutableArray();
=> Channels.OfType<SocketCategoryChannel>().ToImmutableArray();
public SocketGuildUser CurrentUser => _members.TryGetValue(Discord.CurrentUser.Id, out SocketGuildUser member) ? member : null;
public SocketRole EveryoneRole => GetRole(Id);
public IReadOnlyCollection<SocketGuildChannel> Channels
@@ -563,7 +563,7 @@ namespace Discord.WebSocket
await Discord.ApiClient.SendVoiceStateUpdateAsync(Id, channelId, selfDeaf, selfMute).ConfigureAwait(false);
}
catch (Exception)
catch
{
await DisconnectAudioInternalAsync().ConfigureAwait(false);
throw;
@@ -580,7 +580,7 @@ namespace Discord.WebSocket
throw new TimeoutException();
return await promise.Task.ConfigureAwait(false);
}
catch (Exception)
catch
{
await DisconnectAudioAsync().ConfigureAwait(false);
throw;

View File

@@ -1,4 +1,4 @@
using System;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Collections.Immutable;
@@ -28,7 +28,7 @@ namespace Discord.WebSocket
_orderedMessages.Enqueue(message.Id);
while (_orderedMessages.Count > _size && _orderedMessages.TryDequeue(out ulong msgId))
_messages.TryRemove(msgId, out SocketMessage msg);
_messages.TryRemove(msgId, out _);
}
}

View File

@@ -12,12 +12,12 @@ namespace Discord.WebSocket
[DebuggerDisplay(@"{DebuggerDisplay,nq}")]
public class SocketUserMessage : SocketMessage, IUserMessage
{
private readonly List<SocketReaction> _reactions = new List<SocketReaction>();
private bool _isMentioningEveryone, _isTTS, _isPinned;
private long? _editedTimestampTicks;
private ImmutableArray<Attachment> _attachments;
private ImmutableArray<Embed> _embeds;
private ImmutableArray<ITag> _tags;
private List<SocketReaction> _reactions = new List<SocketReaction>();
public override bool IsTTS => _isTTS;
public override bool IsPinned => _isPinned;

View File

@@ -22,8 +22,8 @@ namespace Discord.Net.WebSockets
private readonly SemaphoreSlim _lock;
private readonly Dictionary<string, string> _headers;
private readonly IWebProxy _proxy;
private ClientWebSocket _client;
private IWebProxy _proxy;
private Task _task;
private CancellationTokenSource _cancelTokenSource;
private CancellationToken _cancelToken, _parentToken;