我对创建一个线程并没有多少了解,应该说不懂,希望大侠能够给出一个详细的范例最好。
由于某个函数的操作占资料及耗时长,整个界面都占着没有反应,所以想另创建一个线程去执行该函数。但,需要向函数中传递若干的数据,及函数有一个返回值给调用程序。

解决方案 »

  1.   

    procedure TForm1.Button1Click(Sender: TObject);  //主程序
    var
      mythread : threadxxs;
    begin
     mythread:=threadxxs.Create(database1,memo1);//参数
     mythread.Resume;
    end;//线程
    unit cmxgj;interfaceuses
      Classes,Windows, Messages, SysUtils, Graphics, Controls, Forms, Dialogs,
      StdCtrls ,Grids, DBGrids, Db, DBClient, MConnect, DBTables,DateUtils;type
      threadxxs = class(TThread)
      private
        memo1 : Tmemo;
        database1 : Tdatabase;
        { Private declarations }
      protected
        procedure Execute; override;
        procedure createtable;
        procedure deletetable;
      public
        constructor Create(database : Tdatabase;memo : Tmemo);
      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 threadxxs.UpdateCaption;
        begin
          Form1.Caption := 'Updated in a thread';
        end; }{ threadxxs }constructor threadxxs.Create(database : Tdatabase;memo : Tmemo);
    begin
        memo1:=memo;
        database1:=database;
        FreeOnTerminate:= True;
        inherited Create(False);
    end;
    procedure threadxxs.Execute;
    begin
      //...你的代码
    end;
    end.
      

  2.   

    1. 定义 你要传的数据类型 如果为内定类型则不需要了
    比如
    TEST_INFO = packed record
        id: integer;
        szName: array[0..10] of char;
        sex: BYTE;
      end;
      PTEST_INFO = ^TEST_INFO;
    2. 定义你的线程处理函数
    function ThreadFunc(Para: Pointer):Integer;stdcall;function ThreadFunc(Para: Pointer): Integer; // 注意是全局函数
    var
      t:PTEST_INFO;
    begin
      t := PTEST_INFO(Para); // 然后直接可以获取 其中的数据
      // 下面是你的操作
    end;
    3. 创建线程t.id := 10;
      FillChar(t.szName, 10, 0);
      t.szName := 'abcd';
      t.sex := 0;
      h1 := BeginThread(nil, 1024, @ThreadFunc, @t, 0, dwID);
    end;procedure TForm1.Button3Click(Sender: TObject);
    begin
      TerminateThread(h1, 0);
    end;这样写还是比较简单的,只是一个演示, 真正还要考虑很多 比如时间,资源等的访问
      

  3.   

    从线程中返加值只能用事件, 或者是消息, 向线程中传递值可以结线程定义属性TFooThread = class(TThread)
    private
      FProperty1: ValueType
      FProperty2: ValueType
      FResultProperty: ValuteType;
    protected
      procedrue Execute; override;
    public
      property Property1: ValueType read FProperty1 write FProperty1;
      ...
      property ResultProperty: ValueType read FResultProperty;
    end;传递参数问题得到解决, 就是通过属性, 返回值实际上也是属性, 只不过发个通知给调用者, 可以用同步方法或消息, 好像很简单, 偶就不说了吧