Delphi-线程

碰到身份证阅读器项目,直接放进trimmer里面读卡,导致主页面卡顿,就打算放进子线程里试一下,就有了这个尝试。

1.创建线程文件

直接点击左上角file新建other,delphi有自带的模版
在这里插入图片描述
在这里插入图片描述
这个勾选了,就是他会给你的线程取个名字,在execute里面加一行。

NameThreadForDebugging('线程名字');

在这里插入图片描述

标准模版的代码就是这样,有几个注意事项:
1.文件名得和unit后的保持一致
2.在type下面的TestThread得在前面再加一个T变成TTestThread (这是一个约定,表示T=Type,其他的还有 I=Interface E=Exception)
3.在Execute前的TestThread和2同理

unit TestThread;

interface

uses
  System.Classes;

type
  TTestThread = class(TThread)
  private
    { Private declarations }
  protected
    procedure Execute; override;
  end;

implementation

{ 
  Important: Methods and properties of objects in visual components can only be
  used in a method called using Synchronize, for example,

      Synchronize(UpdateCaption);  

  and UpdateCaption could look like,

    procedure TestThread.UpdateCaption;
    begin
      Form1.Caption := 'Updated in a thread';
    end; 
    
    or 
    
    Synchronize(
      procedure 
      begin
        Form1.Caption := 'Updated in thread via an anonymous method' 
      end
      )
    );
    
  where an anonymous method is passed.
  
  Similarly, the developer can call the Queue method with similar parameters as 
  above, instead passing another TThread class as the first parameter, putting
  the calling thread in a queue with the other thread.
    
}

{ TestThread }

procedure TTestThread.Execute;
begin
  { Place thread code here }
end;

end.

2.使用多线程

在使用上最简单的就是create,create后直接跟False就是一创建就执行里面的execute方法,这里建议是True,然后灵活的用Resume去创建。

procedure TForm1.Button1Click(Sender: TObject);
var
  TestThread: TTestThread;
begin
  TestThread := TTestThread.Create(True);
  TestThread.Resume;
end;

//可简化为:
procedure TForm1.Button1Click(Sender: TObject);
begin
  with TTestThread.Create(True) do Resume;
end;

3.CreateThread

之前直接调用了TThread.Create,其实底层还是CreateThread方法,现在先介绍下他的结构体。

function CreateThread(
  lpThreadAttributes: Pointer;           {安全设置}
  dwStackSize: DWORD;                    {堆栈大小}
  lpStartAddress: TFNThreadStartRoutine; {入口函数}
  lpParameter: Pointer;                  {函数参数}
  dwCreationFlags: DWORD;                {启动选项}
  var lpThreadId: DWORD                  {输出线程 ID }
): THandle; stdcall;                     {返回线程句柄}

4.子标题

正文

在这里插入代码片

5.子标题

正文

在这里插入代码片
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值