Board index » cppbuilder » Thread should have access to main form

Thread should have access to main form


2004-10-30 10:56:46 PM
cppbuilder1
Hi,
I create my own thread class. hier is the structure:
class TMyThread : public TThread
{
public:
void __fastcall Execute();
__fastcall TMyThread(bool CreateSuspended);
};
Here the Code for the funktions:
__fastcall TMyThread::TMyThread(bool CreateSuspended)
: TThread(CreateSuspended)
{
FreeOnTerminate = true;
}
void __fastcall TMyThread::Execute()
{
while(!Terminated)
{
Beep();
ShowMessage(Form1->Caption);
Sleep(5000);
}
}
//--------------------------------------------------------------------------
-
In m MainForm I Have a Button with this code:
void __fastcall TForm1::Button1Click(TObject *Sender)
{
TMyThread *thread = new TMyThread(false);
}
Everythink works fine. all 5 seconds i could hear the beep. then i add the
line ShowMessage(Form1->Caption); to my thread to check, if i can have
access to the main form. when i press the button, my application goes dead.
there is no error message.
where is my problem?? how can i get access to the components auf my main
form?
Tommy
 
 

Re:Thread should have access to main form

"Tommy" < XXXX@XXXXX.COM >wrote in message
Quote
void __fastcall TMyThread::Execute()
{
while(!Terminated)
{
Beep();
ShowMessage(Form1->Caption);
Sleep(5000);
}
Any code that accesses visual information (ShowMessage) is dangerous within
a thread. You must perform those sorts of operations synchronized with the
main application thread. Here is your code revised to work safely.
class TMyThread : public TThread
{
private:
void __fastcall SyncedShow();
protected:
virtual void __fastcall Execute();
public:
__fastcall TMyThread(bool CreateSuspended);
};
__fastcall TMyThread::TMyThread(bool CreateSuspended)
: TThread(CreateSuspended)
{
FreeOnTerminate = true;
}
void __fastcall TMyThread::SyncedShow()
{
ShowMessage(Form1->Caption);
}
void __fastcall TMyThread::Execute()
{
while (!Terminated)
{
Beep();
Synchronize(&SyncedShow);
Sleep(5000);
}
}
HTH,
- Clayton
 

Re:Thread should have access to main form

"Tommy" < XXXX@XXXXX.COM >wrote in message
Quote
ShowMessage(Form1->Caption);
You cannot call ShowMessage() from the context of a worker thread. It is
not thread-safe. It displays a VCL form, and VCL forms do not work properly
outside of the main VCL thread.
If you want a thread-safe message dialog, use the Win32 API's MessageBox()
function instead.
Gambit
 

{smallsort}