C ++构建器中的线程 [英] Threads in C++ builder

查看:92
本文介绍了C ++构建器中的线程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是C ++ Builder的新手,并不熟悉我希望有人可以发布示例或将我指向正确方向的线程。



我有一个表单在C ++ Builder中加载 formShow()函数。它会执行我希望程序执行的操作,但是只有在此之后,它才会显示实际的表单。 。有人可以帮我吗?

解决方案

将逻辑延迟到 OnShow之后可能会更简单事件已退出,根本没有使用线程。例如:

  const UINT WM_DO_WORK = WM_USER +1; 

void __fastcall TForm1 :: FormShow(TObject * Sender)
{
PostMessage(Handle,WM_DO_WORK,0,0);
}

void __fastcall TForm1 :: WndProc(TMessage& Message)
{
if(Message.Msg == WM_DO_WORK)
{
//在这里工作...
}
else
TForm :: WndProc(Message);
}

如果您真的想线程化代码,可以这样:

  class TMyThread:公共TThread 
{
受保护:
virtual void __fastcall Execute() ;
public:
__fastcall TMyThread();
};

__fastcall TMyThread :: TMyThread()
:TThread(true)
{
FreeOnTerminate = true;
//根据需要设置其他线程参数...
}

void __fastcall TMyThread :: Execute()
{
//在这里工作...
//如果需要访问UI控件,
//使用TThread :: Synchornize()方法对该
}

void __fastcall TForm1 :: FormShow(TObject * Sender)
{
TMyThread * thrd = new TMyThread();
thrd-> OnTerminate =& ThreadTerminated;
thrd-> Resume();
}

void __fastcall TForm1 :: ThreadTerminated(TObject * Sender)
{
//线程已完成其工作...
}


I am new to c++ builder and unfamiliar with the threading I was hoping someone could post an example or point me in the right direction.

I have a form which loads the formShow() function in c++ builder. It does what I want my program to do but only after that will it display the actual form.

For this i need to thread the form and the background running of the program. Can anyone help me atall?

解决方案

It might be simplier to just delay your logic until after the OnShow event has exited, without using a thread at all. For example:

const UINT WM_DO_WORK = WM_USER + 1;

void __fastcall TForm1::FormShow(TObject *Sender)
{
    PostMessage(Handle, WM_DO_WORK, 0, 0);
}

void __fastcall TForm1::WndProc(TMessage &Message)
{
    if (Message.Msg == WM_DO_WORK)
    {
        // do work here ...
    }
    else
        TForm::WndProc(Message);
}

If you really want to thread the code, you can do it like this:

class TMyThread : public TThread
{
protected:
    virtual void __fastcall Execute();
public:
    __fastcall TMyThread();
};

__fastcall TMyThread::TMyThread()
    : TThread(true)
{
    FreeOnTerminate = true;
    // setup other thread parameters as needed...
}

void __fastcall TMyThread::Execute()
{
    // do work here ...
    // if you need to access the UI controls,
    // use the TThread::Synchornize() method for that
}

void __fastcall TForm1::FormShow(TObject *Sender)
{
    TMyThread *thrd = new TMyThread();
    thrd->OnTerminate = &ThreadTerminated;
    thrd->Resume();
}

void __fastcall TForm1::ThreadTerminated(TObject *Sender)
{
    // thread is finished with its work ...
}

这篇关于C ++构建器中的线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆