我正在更新 Delphi (Delphi 2009) 代码,它专门使用 TCriticalSection.Acquire/Release
对,而不是 Enter/Release 或 Leave
对。我的问题是 - Acquire
和 Enter
有什么区别?
Delphi 文档非常晦涩——它甚至试图说没有区别:
Acquire: Binds the critical section to the calling thread. Call Acquire to block all other threads from acquiring this critical section until the Release or Leave method is called. Acquire does the same thing as the Enter method.
Enter: Blocks other threads when the calling thread enters a thread-sensitive section. Call Enter to block all other threads from entering code protected by this critical section until the Leave or Release method is called. Enter calls the Acquire method to bind the critical section to the calling thread.
我想要方法 TryAcquire
,但没有这样的方法,所以 - 我正在考虑用 TryEnter 替换我对
循环,受 TryEnter 调用次数的限制。但是要确定会发生什么,我应该知道 Acquire
的所有调用... Sleep...Acquire
和 Enter
之间的区别?这个区别是什么?为什么有两种不同的方法?
最佳答案
对于 TCriticalSection
没有区别。 Enter
被实现为对Acquire
的调用。 Leave
也是如此,它被实现为对 Release
的调用。
TryEnter
方法是在 Delphi 2009 之后添加的。但它只是对 Windows API 调用 TryEnterCriticalSection
的简单包装。您可以自己直接调用该函数。例如,您可以使用类助手将 TryEnter
引入 TCriticalSection
的范围。
关于Delphi TCriticalSection Acquire vs Enter - 有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64063532/