Why am I getting a “handle invalid” while waiting for a thread, which, as I said, ends?

How can I stop the thread correctly when closing the application?

I'm doing it:

procedure TForm1.FormCloseQuery(Sender: TObject; var CanClose: Boolean); begin if not Thread1.Finished then begin Thread1.Terminate; Thread1.WaitFor(); end; end; 

But on Thread1.WaitFor I have an error: "Stream error: handle is invalid (6)." If I WaitForSingleObject (Thread1.Handle, infinite) instead of WaitFor, everything is fine.

Why, if I use Thread.freeonterminate: = false, then WaitFor works well? Please explain to me what I am doing wrong. As far as I understand, I need to use "if Assigned" instead of "if not Thread1.Finished", right?

+6
source share
1 answer

When you set FreeOnTerminate = True , the thread object is automatically freed when it completes. Thus, after its completion, any further calls to this object are invalid. Once you call Terminate , you must assume that the object no longer exists.

If you need to perform further operations on a stream after it starts, do not install FreeOnTerminate . Instead, manually release it after you have actually finished using it.

The only time you would use Assigned is that you expect Thread1 be nil . Have you ever assigned Thread1 := nil ? If not, then you should not expect it to receive this value. As you should know, variables do not change their values ​​when calling methods on them. But if you installed FreeOnTerminate , then it is also incorrect to check the Finished property, because it may have already finished and freed itself.

+11
source

Source: https://habr.com/ru/post/890269/


All Articles