When calling the TryEnter method on a TCriticalSection the result is always true. Surely this should only return true if it is able to aquire the lock?
var
MyCritSect: TCriticalSection;
begin
MyCritSect := TCriticalSection.Create;
try
// MyCritSect.Enter;
Writeln(BoolToStr(MyCritSect.TryEnter, True)); // This should return True
Writeln(BoolToStr(MyCritSect.TryEnter, True)); // This should return False?
Readln;
except
on E: Exception do
Writeln(E.ClassName, ': ', E.Message);
end;
end.
Even if you uncomment the MyCritSect.Enter;
line it still returns True for both calls to TryEnter.
I am using Delphi XE and Windows 10.
Critical sections are re-entrant locks. From the documentation:
When a thread owns a critical section, it can make additional calls to EnterCriticalSection or TryEnterCriticalSection without blocking its execution. This prevents a thread from deadlocking itself while waiting for a critical section that it already owns.
Your call to TryEnter
will fail if made from a different thread, and the first thread already owns the lock.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With