Have you ever written programs that their
GUI stops to
respond because a process blocks program execution in a point
in your code? (For example blocking sockets)
If so, you can solve this problem with multi thread
programming. Windows can run multiple paths in your program
at once. So you can do your blocking operations in one thread
and GUI operations in main thread.
They will run without interrupting each other. Example
program is written in C++ Builder but it can be ported to
Delphi with small changes.
But be careful. Running VCL GUI codes are not thread safe so
we must run them inside a Synchronize() function call. This
will run unsafe functions with threads in mind, so the result
is a safe code.
You can download both C++ Builder and Delphi source codes
from this address :
and now the code ...
1- Create a normal project. Save Form1 unit as Unit1.
2- Add a new thread object (File->New->Thread Object.
Now save Thread unit as Unit2.
3- Unit1 code is : ( headers excluded )
__fastcall TForm1::TForm1(TComponent* Owner)
void __fastcall TForm1::Button1Click(TObject *Sender)
TTestThread *MyThread=new TTestThread(False);
//false starts thread on creation , True will suspend it
4- Unit2 code is : ( headers excluded )
__fastcall TTestThread::TTestThread(bool CreateSuspended)
void __fastcall TTestThread::Execute()
void __fastcall TTestThread::UpdateTextBox()
5- Now run program and test to see if main form stops to
respond to your actions. It will not !. If you use
Sleep function in main thread ( main form ) in a loop ,
Form1 will freeze. We used Sleep function in a separate
thread therefore form will not freeze anymore.
As you see writing multi thread programs in C++ Builder and
Delphi is very easy. But know that writing thread programs
needs enough care. You must write thread safe code in thread
units. You must also prepare yourself for unordinary errors.
I wish this article be useful for those with complicated
freezing programs !!!