Skip to content

NET-2626 New Rule Idea: Synchronization objects should be released in a finally block #9769

@jhinder

Description

@jhinder

Description

Synchronization types like Semaphore[Slim], Mutex etc. should be used with try/finally after acquiring the lock, with the release operation happening in the finally block. If an exception occurs in the guarded section, the release operation is never called, leaving the object locked for longer than necessary, potentially even forever (deadlock). The finally block guarantees that the lock is always released.

Noncompliant code snippet

private readonly SemaphoreSlim _semaphore;

// ------
await _semaphore.WaitAsync();
// The synchronized code
_semaphore.Release();

Compliant code snippet

private readonly SemaphoreSlim _semaphore;

// ------
await _semaphore.WaitAsync();
try
{
    // The synchronized code
}
finally
{
    _semaphore.Release();
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    Rule IdeaIdea for a rule that has NOT been specified.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions