All Downloads are FREE. Search and download functionalities are using the official Maven repository.

org.sonar.plugins.vbnet.S7131.html Maven / Gradle / Ivy

There is a newer version: 10.5.0.109200
Show newest version

When using ReaderWriterLock and ReaderWriterLockSlim for managing read and write locks, you should not release a read lock while holding a write lock and vice versa, otherwise you might have runtime exceptions. The locks should be always correctly paired so that the shared resource is accessed safely.

This rule raises if:

Why is this an issue?

If you use the ReaderWriterLockSlim class, you will get a LockRecursionException. In the case of ReaderWriterLock, you’ll get a runtime exception for trying to release a lock that is not owned by the calling thread.

Code examples

Noncompliant code example

Public Class Example

    Private Shared rwLock As New ReaderWriterLock()

    Public Sub Writer()
        rwLock.AcquireWriterLock(2000)
        Try
            ' ...
        Finally
            rwLock.ReleaseReaderLock() ' Noncompliant, will throw runtime exception
        End Try
    End Sub

    Public Sub Reader()
        rwLock.AcquireReaderLock(2000)
        Try
            ' ...
        Finally
            rwLock.ReleaseWriterLock() ' Noncompliant, will throw runtime exception
        End Try
    End Sub

End Class

Compliant solution

Public Class Example

    Private Shared rwLock As New ReaderWriterLock()

    Public Shared Sub Writer()
        rwLock.AcquireWriterLock(2000)
        Try
            ' ...
        Finally
            rwLock.ReleaseWriterLock()
        End Try
    End Sub

    Public Shared Sub Reader()
        rwLock.AcquireReaderLock(2000)
        Try
            ' ...
        Finally
            rwLock.ReleaseReaderLock()
        End Try
    End Sub

End Class

Resources

Documentation





© 2015 - 2025 Weber Informatics LLC | Privacy Policy