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

问题描述 投票:0回答:1

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

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

#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!");
}
//---------------------------------------------------------------------------

标题

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

#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!"),并运行了该程序,但是除了显示我的表单之外,什么都没有发生。

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

multithreading c++builder vcl
1个回答
1
投票

我必须用此替换ShowMessage("Hello World!")行:

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

并以此创建线程:

MyThreadClass* myThread = new MyThreadClass(false); // false == don't create suspended
© www.soinside.com 2019 - 2024. All rights reserved.