TThread执行自定义函数

来源:互联网 发布:js读取本地文件到流 编辑:程序博客网 时间:2024/06/08 08:42

1、线程定义

#ifndef MyThreadH
#define MyThreadH
#include <Classes.hpp>
class threadMy : public TThread
{
private:
protected:
        void __fastcall Execute();
public:
   TThreadMethod  myMethod;
        __fastcall threadMy(bool CreateSuspended);
        void __fastcall UpdateCaption();
        void __fastcall SetFunPoint(TThreadMethod  myNewMethod); //自定义函数指针
__property    Terminated;
     bool     RunFunctioning;//true 正在运行函数 false  运行结束
};
#endif

 

cpp文件

#include <vcl.h>
#pragma hdrstop

#include "MyThread.h"
#include "Unit1.h"
#pragma package(smart_init)
__fastcall threadMy::threadMy(bool CreateSuspended)
        : TThread(CreateSuspended)
{
   RunFunctioning = false;
}

void __fastcall threadMy::Execute()
{
   //typedef void __fastcall (__closure *TThreadMethod)(void);
   //Sleep(5000);
   //Synchronize(myMethod);
   myMethod();//不会引起无响应
   //Synchronize(UpdateCaption);//会有无响应
}

void __fastcall threadMy::UpdateCaption()
{
   //   Form1->Caption = Now();
   Sleep(5000);
}
void __fastcall threadMy::SetFunPoint(TThreadMethod  myNewMethod)
{
   myMethod = NULL;
   myMethod = myNewMethod;
}

 

调用实例

class TForm1 : public TForm
{

public:  // User declarations
        __fastcall TForm1(TComponent* Owner);
        void __fastcall runQuery1();
        void __fastcall runQuery2();
        void __fastcall RunFunByThread(TThreadMethod  myNewMethod);
};

 

void __fastcall TForm1::RunFunByThread(TThreadMethod  myNewMethod)
{
   if( tr )
   {
      if( tr->RunFunctioning )
         return;
      tr->Terminate();
      delete tr;
      tr = NULL;
   }
   if( tr == NULL)
      tr = new threadMy(true);
   tr->SetFunPoint(myNewMethod);
   tr->Resume();
//      tr->WaitFor();
//      tr->RunFunctioning = true;
//      tr->RunFunctioning=false;
//   tr->Terminated;
}

 

 

void __fastcall TForm1::Button1Click(TObject *Sender)
{
   Caption = "";
   start = 0;
   RunFunByThread(runQuery1);//函数1
}

 

void __fastcall TForm1::Button2Click(TObject *Sender)
{
   Caption = "";
   start = 0;
   RunFunByThread(runQuery2); //函数2
}

两个函数,可以自定义,切换

自定义代码写在当前类窗体中,不用写到线程thread里了

一个工程中可以包含线程头文件,公用一个线程单元文件,不用重复写线程代码

 

 

原创粉丝点击