Delphi TThread.CurrentThread and EAccessViolation - Is This a Bug or My Incompetence..?

delphi, delphi-2009, tthread

Solution

Unfortunately it seems like a bug linked to the call order of the finalization section in the Classes unit:

`DoneThreadSynchronization` clears the `ThreadLock` structure, then `FreeExternalThreads` wants to destroy the Thread object you just created when calling `CurrentThread`, and that requires the ThreadLock to be already initialized in the call to `EnterCriticalSection(ThreadLock)` in `TThread.RemoveQueuedEvents`...

UPDATE: There is now a workaround patch in the QC report.

Problem

In Delphi 2009 I'm finding that any time I use TThread.CurrentThread in an application, I'll get an error message like the following when the application closes: ``` Exception EAccessViolation in module ntdll.dll at 0003DBBA. Access violation at address 7799DBBA in module 'ntdll.dll'. Write of address 00000014. ``` Unless it's just my machine, you can replicate this in a few seconds: create a new Delphi Forms Application, add a button to the form, and use something like the following for the button's event handler: ``` procedure TForm1.Button1Click(Sender: TObject); begin TThread.CurrentThread; end; ``` On both my Vista machine and my XP machine I'm finding that, if I don't click the button everything's fine, but if I do click the button I get the above error message when I close the application. So... I'm wondering if this is a bug, but at the same time I think it's rather likely that I'm simply not understanding something very basic about how you're supposed to work with TThreads in Delphi. I am a bit of a Delphi newbie I'm afraid. Is there something obviously wrong with using TThread.CurrentThread like that? If not, and you have Delphi 2009, do you get the same problem if you implement my simple sample project? Update: As François noted below, this actually is a bug in Delphi 2009 at the moment - you can vote for it here. Update: This bug was fixed in Delphi 2010.

Original source