Xojo.Threading.CriticalSection

From Xojo Documentation

Revision as of 18:18, 17 August 2018 by PLefebvre (talk | contribs) (Created page with "{{ClassBox | super=Object | scope=global }} {{Description | text=Used to protect a single resource in a multithreaded environment.}} <dynamicTable id="Methods" class="met...")
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)

Class (inherits from Object)

Used to protect a single resource in a multithreaded environment.

Methods
Enter Leave TryEnter

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.

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 View that contains the control that calls the threads.
  • In the Run event handler of the Thread, call Enter and Leave before and after the code that tries to access the shared resource.

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

Sample Code

For example, if you have a logging file that multiple threads are writing to you may want to ensure that only a single thread has the file open for writing at one time. You could do this by having a WriteLog method that opens the file if it can get the lock. A property called LogFileAvailable As CriticalSection is initialized by the thread:

LogFileAvailable = New CriticalSection

And then a method can check it before it attempts to open the log file for writing:

Sub LogInfo(logText As Text)
If LogFileAvailable.TryEnter Then
Dim file As FolderItem = SpecialFolder.Documents.("log.txt")
file = TextOutputStream.Append(file, Encodings.UTF8)
file.WriteLine(logText)
file.Close
LogFileAvailable.Leave
End If
End Sub

See Also

Xojo.Threading.Semaphore, Xojo.Threading.Thread classes