Skip to content

Commit d750f35

Browse files
committed
尝试修复一个CancellationToken.Register导致内存泄漏问题
1 parent c0e928e commit d750f35

File tree

1 file changed

+14
-1
lines changed

1 file changed

+14
-1
lines changed

Quick.Protocol/QpServerChannel.cs

Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@ public class QpServerChannel : QpChannel
1313
{
1414
private readonly Stream stream;
1515
private readonly CancellationTokenSource cts;
16+
private readonly CancellationToken serverCancellationToken;
1617
private readonly QpServerOptions options;
1718
private readonly string channelName;
1819
//通过认证后,才允许使用的命令执行管理器列表
@@ -38,9 +39,9 @@ public QpServerChannel(Stream stream, string channelName, CancellationToken canc
3839
this.options = options;
3940
this.authedCommandExecuterManagerList = options.CommandExecuterManagerList;
4041
this.authedNoticeHandlerManagerList = options.NoticeHandlerManagerList;
42+
serverCancellationToken = cancellationToken;
4143

4244
cts = new CancellationTokenSource();
43-
cancellationToken.Register(Stop);
4445

4546
//初始化连接相关指令处理器
4647
var connectAndAuthCommandExecuterManager = new CommandExecuterManager();
@@ -57,6 +58,8 @@ public QpServerChannel(Stream stream, string channelName, CancellationToken canc
5758
BeginReadPackage(token);
5859
//开始统计网络数据
5960
_ = BeginNetstat(token);
61+
//开始检查服务端的取消令牌
62+
_ = BeginCheckServerCancellationToken(token);
6063

6164
//如果认证超时时间后没有通过认证,则断开连接
6265
if (options.AuthenticateTimeout > 0)
@@ -79,6 +82,16 @@ public QpServerChannel(Stream stream, string channelName, CancellationToken canc
7982
});
8083
}
8184

85+
private async Task BeginCheckServerCancellationToken(CancellationToken cancellationToken)
86+
{
87+
while (!cancellationToken.IsCancellationRequested)
88+
{
89+
await Task.Delay(1000, cancellationToken);
90+
if (serverCancellationToken.IsCancellationRequested)
91+
Stop();
92+
}
93+
}
94+
8295
private Commands.Connect.Response connect(QpChannel handler, Commands.Connect.Request request)
8396
{
8497
if (request.InstructionIds != null)

0 commit comments

Comments
 (0)