我有一个 TidTCPServer,它在 onExcecute 事件中使用数据库操作(通过使用 TidNotify)。一切都很好,而不是可能关闭应用程序。 在关闭应用程序期间,我不知道所有通知实例是否完成了工作,通常我会收到运行时错误 216(我认为我在“通知”工作结束之前关闭数据库)。 有什么方法可以检查 - 是否有等待旧的通知帖子或不确定我可以关闭应用程序。 另一个问题是如何保护 TidTCPServer 在关闭服务器进程期间不接受新连接。 我使用如下代码,但仍然收到错误。
type
TShutdownThread = class(TThread)
protected
procedure Execute; override;
end;
procedure TShutdownThread.Execute;
begin
IdTCPServer.Active := false;
end;
//closing...
if IdTCPServer.Active then
begin
with TShutdownThread.Create(false) do
try
WaitFor; // internally processes sync requests...
finally
Free;
end;
end;
最佳答案
有什么方法可以检查 - 有吗 等待旧的通知帖子或不确定我可以关闭 应用程序。
TIdNotify
是异步的,它将请求发送到主线程消息队列以便稍后执行。 TShutdownThread.WaitFor()
退出后,挂起的请求可能仍在队列中。您可以调用 RTL 的 CheckSynchronize()
函数来处理任何剩余的请求,例如:
if IdTCPServer.Active then
begin
with TShutdownThread.Create(false) do
try
WaitFor;
finally
Free;
end;
CheckSynchronize;
end;
如何保护 TidTCPServer 在关闭服务器进程期间不接受新连接。
当 TIdTCPServer
被停用时,它会为您关闭其监听端口。然而,在服务器关闭端口之前接受新客户端的机会非常小。服务器将在关闭过程中关闭这些连接,但如果您不希望为这些连接调用 OnExecute 事件,那么您可以在停用服务器之前在代码中的某个位置设置一个标志,然后检查 OnConnect
事件中的该标志,如果设置了该标志,则立即断开客户端连接,例如:
var
ShuttingDown: boolean = False;
procedure TForm1.IdTCPServer1Connect(AContext: TIdContext);
begin
if ShuttingDown then
begin
AContext.Connection.Disconnect;
Exit;
end;
...
end;
...
if IdTCPServer.Active then
begin
ShuttingDown := True;
try
with TShutdownThread.Create(false) do
try
WaitFor;
finally
Free;
end;
CheckSynchronize;
finally
ShuttingDown := False;
end;
end;
关于connection - Indy、TidNotify 和关闭 TidTCPServer,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14909996/