Skip to content

Commit

Permalink
improved the disposing of server
Browse files Browse the repository at this point in the history
  • Loading branch information
kerryjiang committed Jan 26, 2025
1 parent e313305 commit 2028d16
Show file tree
Hide file tree
Showing 4 changed files with 30 additions and 2 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ namespace SuperSocket.Server.Abstractions.Connections
{
public delegate ValueTask NewConnectionAcceptHandler(ListenOptions listenOptions, IConnection connection);

public interface IConnectionListener
public interface IConnectionListener : IDisposable
{
ListenOptions Options { get; }

Expand Down
12 changes: 11 additions & 1 deletion src/SuperSocket.Server/Connection/TcpConnectionListener.cs
Original file line number Diff line number Diff line change
Expand Up @@ -131,7 +131,7 @@ public Task StopAsync()
var listenSocket = _listenSocket;

if (listenSocket == null)
return Task.Delay(0);
return Task.CompletedTask;

_stopTaskCompletionSource = new TaskCompletionSource<bool>();

Expand All @@ -145,5 +145,15 @@ public override string ToString()
{
return Options?.ToString();
}

public void Dispose()
{
var listenSocket = _listenSocket;

if (listenSocket != null && Interlocked.CompareExchange(ref _listenSocket, null, listenSocket) == listenSocket)
{
listenSocket.Dispose();
}
}
}
}
8 changes: 8 additions & 0 deletions src/SuperSocket.Server/SuperSocketService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -555,6 +555,14 @@ protected virtual async ValueTask DisposeAsync(bool disposing)
{
_logger.LogError(e, "Failed to stop the server");
}

if (_connectionListeners.Any())
{
foreach (var listener in _connectionListeners)
{
listener.Dispose();
}
}
}

disposedValue = true;
Expand Down
10 changes: 10 additions & 0 deletions src/SuperSocket.Udp/UdpConnectionListener.cs
Original file line number Diff line number Diff line change
Expand Up @@ -224,5 +224,15 @@ public override string ToString()
{
return Options?.ToString();
}

public void Dispose()
{
var listenSocket = _listenSocket;

if (listenSocket != null && Interlocked.CompareExchange(ref _listenSocket, null, listenSocket) == listenSocket)
{
listenSocket.Dispose();
}
}
}
}

0 comments on commit 2028d16

Please sign in to comment.