Stop crashing on reconnect

This commit is contained in:
Brandon Smith
2015-08-23 04:33:06 -03:00
parent 9f2b305a19
commit a7fa1e48d6
2 changed files with 14 additions and 16 deletions

View File

@@ -66,7 +66,7 @@ namespace Discord
/// <summary> Initializes a new instance of the DiscordClient class. </summary> /// <summary> Initializes a new instance of the DiscordClient class. </summary>
public DiscordClient(DiscordClientConfig config = null) public DiscordClient(DiscordClientConfig config = null)
{ {
_blockEvent = new ManualResetEventSlim(false); _blockEvent = new ManualResetEventSlim(true);
_config = config ?? new DiscordClientConfig(); _config = config ?? new DiscordClientConfig();
_rand = new Random(); _rand = new Random();
@@ -869,13 +869,6 @@ namespace Discord
{ {
await _webSocket.DisconnectAsync(); await _webSocket.DisconnectAsync();
//Do not clean up until all tasks have ended
_webSocket.Dispose();
_webSocket = null;
_blockEvent.Dispose();
_blockEvent = null;
_tasks = null;
//Clear send queue //Clear send queue
Message ignored; Message ignored;
while (_pendingMessages.TryDequeue(out ignored)) { } while (_pendingMessages.TryDequeue(out ignored)) { }
@@ -885,7 +878,10 @@ namespace Discord
_roles.Clear(); _roles.Clear();
_servers.Clear(); _servers.Clear();
_users.Clear(); _users.Clear();
});
_blockEvent.Set();
_tasks = null;
}).Unwrap();
_isConnected = true; _isConnected = true;
} }
else else
@@ -895,10 +891,11 @@ namespace Discord
/// <summary> Disconnects from the Discord server, canceling any pending requests. </summary> /// <summary> Disconnects from the Discord server, canceling any pending requests. </summary>
public async Task Disconnect() public async Task Disconnect()
{ {
_blockEvent.Set();
if (_tasks != null) if (_tasks != null)
await _tasks; {
try { _disconnectToken.Cancel(); } catch (NullReferenceException) { }
try { await _tasks; } catch (NullReferenceException) { }
}
} }
//Servers //Servers

View File

@@ -58,7 +58,6 @@ namespace Discord
_webSocket = null; _webSocket = null;
_disconnectToken.Dispose(); _disconnectToken.Dispose();
_disconnectToken = null; _disconnectToken = null;
_tasks = null;
//Clear send queue //Clear send queue
byte[] ignored; byte[] ignored;
@@ -69,6 +68,8 @@ namespace Discord
_isConnected = false; _isConnected = false;
RaiseDisconnected(); RaiseDisconnected();
} }
_tasks = null;
}); });
if (autoLogin) if (autoLogin)
@@ -109,8 +110,8 @@ namespace Discord
{ {
if (_tasks != null) if (_tasks != null)
{ {
_disconnectToken.Cancel(); try { _disconnectToken.Cancel(); } catch (NullReferenceException) { }
await _tasks; try { await _tasks; } catch (NullReferenceException) { }
} }
} }