Class

CriticalSection


Description

Used to protect a resource in a multithreaded environment.

Methods

Name

Parameters

Returns

Shared

Enter

Leave

TryEnter

Boolean

Method descriptions


CriticalSection.Enter

Enter

Attempts to get a lock on the resource managed by the CriticalSection.

When the call to Enter succeeds, the function returns and your code has exclusive access to the protected resource. If the lock cannot be obtained immediately, Enter will block the current thread from continuing to run. It will wait for the resource to become available.

Enter differs from the Signal method of the Semaphore class in that it can be called multiple times from the currently executing thread. If the calling thread already owns the lock, the method returns immediately. This makes CriticalSections very useful for calling a method recursively.


CriticalSection.Leave

Leave

Call Leave when you are finished using the protected resource and you want to give it back to the CriticalSection.

Every time you call Enter or TryEnter and succeed, you must call Leave. This includes calling it recursively. Otherwise the resource will be protected indefinitely.


CriticalSection.TryEnter

TryEnter As Boolean

Attempts to get a lock on the resource managed by the CriticalSection.

TryEnter is similar to Enter but returns a Boolean. If it succeeds, it returns True and the thread has exclusive use of the resource. If it fails, it returns False but does not block execution of the thread.

Notes

A CriticalSection is similar to a Semaphore, except a CriticalSection protects only one resource. The Semaphore class, on the other hand, can protect more than one resource. The Mutex class is similar to a CriticalSection, but its scope is all the applications that are running on the user's computer, not just the current application. You can use a Mutex, for example, check whether another copy of the application is running and is using a needed resource.

You use critical sections in conjunction with Threads. In a situation in which two or more of the threads might try to access the same item, then you should enclose the code with calls to the Enter (or TryEnter) and Leave methods.

One strategy is this:

  • Create a subclass of Thread which does the operations that might compete for access to a resource.

  • Create a CriticalSection property of Public scope in, for example, the window that contains the control that calls the threads.

  • In the Run event handler of the Thread, call Enter (to get ownership and lock the resource) and Leave (to release ownership and the lock) before and after the code that tries to access the shared resource.

If a thread that has an ownership lock crashes, the lock is not released.

Compatibility

All project types on all supported operating systems.

See also

Object parent class; Mutex, Semaphore, Thread classes