使用Spcomm串口通信,发送数据时,创建一个线程(手动释放),在收到一组数据后,创建一个线程(自动释放)将收到的数据写入paradox数据库(此部分写在dll中)。但是在关闭dll返回主程序,主程序无响应。调试时,一直运行到窗口关闭都未报错,程序代码如下,请高手指点:
窗口关闭代码:
procedure TFrmMain.FormClose(Sender: TObject; var Action: TCloseAction);
begin
sendstop:=true;
timerstop;
deletecriticalsection(cs);
if assigned(tsend) then tsend.Free;
  alist.Destroy;
  comm1.StopComm;
...//其他操作
end;spcom接收到数据时创建线程procedure TFrmMain.Comm1ReceiveData(Sender: TObject; Buffer: Pointer;
  BufferLength: Word);
Type
arr=^integer;
var
RevP: array [1..4096] of byte ;
i:integer;
CommRevStr:AnsiString;
begin
     ...  //接收到数据处理
if not sendstop then
begin
    case start of
    1:  begin
          start:=2;
          Twrite:=Twritedata.Create(ti,7,0,commrevstr);//创建线程
        end ;
    3:  begin
          start:=0;
          Twrite:=Twritedata.Create(ti,ti-7,1,commrevstr) ;//创建线程
        end;
    end;
end
end;
接收数据线程Constructor TWriteData.Create(tport,tcount,tindex:integer;tAstr:AnsiString);
begin
    CoInitialize( nil );
     fquery:=Tquery.Create(nil);
     fquery.SessionName:=frmmain.Session1.SessionName;
    port:=tport;
    count:=tcount;
    Astr:=TAstr;
    index:=tindex;
    inherited create(false);
    FreeOnTerminate:=True;    
end;destructor TWriteData.Destroy;
begin
  FQuery.FREE;
  CoUnInitialize;
inherited destroy;
end;procedure  TWriteData.Execute;
var
...//定义
begin
k:=2;
for i:=1 to count do
begin
  try
      ...//数据处理
  except
      sendstop:=true;
      application.MessageBox('接收数据错误(出现乱码)'+#13+'请检查串口数据线连接!'+#13+'或尝试调整采样时间!','系统提示',mb_ok);
      break;
  end;
try
       case index of
       0:pport:=i;
       1:pport:=i+7;
       2:pport:=i+14;
       end;
       begin
          ....//fquery的操作
       end;
                 if not table then   LocalPicWrite(pport,D01,D02,D03,D04);
except
      application.MessageBox('数据库写入错误!','系统提示',mb_ok);
end;
end;
end ;
end;
发送指令线程
Constructor TSendCommand.Create;
begin
    CoInitialize( nil );
    inherited Create(True);
end;
destructor TSendCommand.Destroy;
begin
  CoUnInitialize;
inherited destroy;
end;
procedure TSendCommand.Execute;
begin
repeat
if (not sendstop) then
begin
   try
    ....//发送命令
    except
                    SendStop:=true;
                    application.MessageBox('发送数据错误,请检查串口接线!','系统提示',mb_ok);
    end;
end;
sleep(500);
until Terminated;
end;另外:
procedure TFrmMain.FormDestroy(Sender: TObject);
begin
if assigned(tsend) then    tsend.Free;//只要把这句写在这里,关闭时程序就无响应,
end;

解决方案 »

  1.   

    关闭线程,用tsend.Terminate;不是free
      

  2.   

    terminate只是终止线程运行,没有释放出来
      

  3.   

    terminate只是终止线程运行,没有释放出来
      

  4.   


    引用楼主 的回复:
    使用Spcomm串口通信,发送数据时,创建一个线程(手动释放),在收到一组数据后,创建一个线程(自动释放)将收到的数据写入paradox数据库(此部分写在dll中)。但是在关闭dll返回主程序,主程序无响应。调试时,一直运行到窗口关闭都未报错,程序代码如下,请高手指点:
    窗口关闭代码:
    procedure TFrmMain.FormClose(Sender: TObject; var Acti……
    terminate只是终止线程运行,没有释放出来
      

  5.   

    其实,你可以用api函数,直接关闭掉程序,就一切清净了。
      

  6.   

    复杂的东西,一下子清净了。强大的 API