我使用Indy进行TCP通信(D2009,Indy 10)。
在评估客户端请求后,我希望向客户端发送答复。因此,我存储TIdContext,如下所示(伪代码):
在评估客户端请求后,我希望向客户端发送答复。因此,我存储TIdContext,如下所示(伪代码):
procedure ConnectionManager.OnIncomingRequest (Context : TIdContext);
begin
Task := TTask.Create;
Task.Context := Context;
ThreadPool.AddTask (Task);
end;
procedure ThreadPool.Execute (Task : TTask);
begin
// Perform some computation
Context.Connection.IOHandler.Write ('Response');
end;
但是,如果客户端在请求和准备发送答案之间终止连接怎么办?如何检查上下文仍然有效?我尝试过
if Assigned (Context) and Assigned (Context.Connection) and Context.Connection.Connected then
Context.Connection.IOHandler.Write ('Response');
但是这并没有帮助。在某些情况下,程序会挂起,如果我暂停执行,就可以看到当前行是if条件语句所在的行。
这里发生了什么?如何避免尝试使用已失效的连接发送信息?