There are two ways to release threads: one is to automatically release a thread after it finishes running, and one to release it manually.
Whatever the release, it should be released after the thread has stopped.
However, there are two ways to stop a thread: one is to do it without setting a flag bit, and one is to do so by looping through the Execute method and setting the flag bit to stop.
If the thread has stopped and is automatically released and then stopped manually, an error will be made.
Here's a look at the code:
1. Automatically release the thread after auto stop:
Constructor Ttestthread.create;begin inherited Create (True); Freeonterminate: = True;end;procedure ttestthread.execute;begin ....// function code //This method completes after the thread has stopped end;
In this case, the thread is automatically freed, so do not release it manually, or you will get an error
2. Automatically release threads after manual stop:
Constructor Ttestthread.create;begin inherited Create (True); Freeonterminate: = True;end;procedure ttestthread.execute;begin While not Terminated does//not Terminated do Begin ...//function code end;end;procedure testbegin T1: = Ttestthread.create (self); T1. Terminate;end;
3. Manually released Threads:
Constructor Ttestthread.create;begin inherited Create (True); End;procedure Ttestthread.execute;begin while Not Terminated does//not Terminated do begin ...//function code end;end;procedure testbegin T1: = Ttestthread.create (self); T1. Terminate; T1. WaitFor; T1. Free;end;
So, when to use automatically freed threads, when to use manually freed threads?
My advice is to:
If the thread runs for a short time or is guaranteed to run before the system exits, you can choose to automatically release it, as it will automatically release
If this thread runs throughout the system, choose to manually release the
Pc100_net's Blog
Http://blog.ifeng.com/article/35055412.html
Introduction to the release of the Delphi thread [go]