在 C++ Builder 中,如何在 `TThread` 中执行一个函数?

In C++ Builder, how to execute a function inside a `TThread`?

我使用 File > New > Other > Thread Object 菜单创建了 TThread。它给了我一些样板代码,像这样:

//---------------------------------------------------------------------------

#include <System.hpp>
#pragma hdrstop

#include "Unit2.h"
#pragma package(smart_init)
//---------------------------------------------------------------------------

//   Important: Methods and properties of objects in VCL can only be
//   used in a method called using Synchronize, for example:
//
//      Synchronize(&UpdateCaption);
//
//   where UpdateCaption could look like:
//
//      void __fastcall MyThreadClass::UpdateCaption()
//      {
//        Form1->Caption = "Updated in a thread";
//      }
//---------------------------------------------------------------------------

__fastcall MyThreadClass::MyThreadClass(bool CreateSuspended)
    : TThread(CreateSuspended)
{
}
//---------------------------------------------------------------------------
void __fastcall MyThreadClass::Execute()
{
    NameThreadForDebugging(System::String(L"MyThread"));
    //---- Place thread code here ----
    ShowMessage("Hello World!");
}
//---------------------------------------------------------------------------

header

//---------------------------------------------------------------------------

#ifndef Unit2H
#define Unit2H
//---------------------------------------------------------------------------
#include <System.Classes.hpp>
//---------------------------------------------------------------------------
class MyThreadClass : public TThread
{
protected:
    void __fastcall Execute();
public:
    __fastcall MyThreadClass(bool CreateSuspended);
};
//---------------------------------------------------------------------------
#endif

我添加了您可以看到的行,ShowMessage("Hello World!"),和 运行 程序,但是除了显示我的表单之外没有任何反应。

如何在我的线程函数中执行代码?

我不得不用这个替换 ShowMessage("Hello World!") 行:

Synchronize([](){ ShowMessage("Hello World!"); });

并以此创建线程:

MyThreadClass* myThread = new MyThreadClass(false); // false == don't create suspended