roslynator icon indicating copy to clipboard operation
roslynator copied to clipboard

Analyzer + codefix: Mark objects used for locking as readonly (new or RCS1169 derivative)

Open IanKemp opened this issue 7 years ago • 0 comments
trafficstars

Consider:

object locker = new object();

void LockedAction()
{
    lock (locker)
    {
        // ... do something requiring locking...
    }
}

But any code can reassign the value of locker:

void SomethingElse()
{
    locker = new object();
}

The end result is that LockedAction is no longer thread-safe and Bad Things™ will happen when it is invoked concurrently.

To prevent this bug, locker should be declared as readonly so that it can never be reassigned:

readonly object locker = new object();

void SomethingElse()
{
    locker = new object(); // compile error
}

I'm aware this is already covered by RSC1169, but this is a special and IMO more important case.

IanKemp avatar Apr 11 '18 05:04 IanKemp