• Delphi中线程的释放介绍[转]


    线程的释放方式有两种:一种是线程在运行完成后自动释放,一种是手动释放。

    无论是那种释放,都应该在线程停止后进行释放。

    然而线程的停止也有两种情况:一种是不需要设置标志位,直接完成;一种是由于execute方法中做了循环,需要设置标志位才能停止。

    如果线程已经停止并且自动释放,再去手动停止,就会报错。

    下面看代码:

    1、自动停止后自动释放的线程:

    constructor TTestThread.Create;begin  inherited Create( True );  FreeOnTerminate := True;end;procedure TTestThread.Execute;begin    ....//功能代码    //此方法完成后线程就已经停止了end;

    这种情况线程会自动释放,因此不要手动释放,否则会报错

    2、手动停止后自动释放的线程:

    constructor TTestThread.Create;begin  inherited Create( True );  FreeOnTerminate := True;end;procedure TTestThread.Execute;begin  while not Terminated do //not Terminated do  begin    ....//功能代码  end;end;procedure Testbegin    t1 := TTestThread.Create( Self );    t1.Terminate;end;

    3、手动释放的线程:

    constructor TTestThread.Create;begin  inherited Create( True );end;procedure TTestThread.Execute;begin  while not Terminated do //not Terminated do  begin    ....//功能代码  end;end;procedure Testbegin    t1 := TTestThread.Create( Self );    t1.Terminate;    t1.WaitFor;    t1.Free;end;

    那么,何时使用自动释放的线程,何时使用手动释放的线程呢

    我的建议是:

    如果这个线程运行时间很短或者能保证在系统退出前完成运行,则可以选择自动释放,因为它可以很快自动释放掉

    如果这个线程运行贯穿系统运行整个期间,则要选择手动释放了

    pc100_net的博客 

     

    http://blog.ifeng.com/article/35055412.html

  • 相关阅读:
    HTML 转 PDF 之 wkhtmltopdf 工具精讲
    oracle学习之数据库数据保存成文件
    字体单位大小对照换算表(字号、磅、英寸、像素)
    mui 注意事项
    hbuilder header消失
    C# salt+hash 加密
    判断二个文件是否相同
    html转pdf
    Oracle中Clob类型处理解析:ORA-01461:仅可以插入LONG列的LONG值赋值
    【Django】Django 直接执行原始SQL 如何防止SQL注入 ?
  • 原文地址:https://www.cnblogs.com/python001/p/4307294.html
Copyright © 2020-2023  润新知