Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# - ReSharper 9.x flagging code with new warning - "Inconsistent synchronization on field"

Tags:

c#

resharper

The code below running RS 8.2.x inspection has no issues; after running RS 9.x inspection on it, RS give this warning: "The field is sometimes used inside synchronized block and sometimes used without synchronization."

// The wait time determines if we block on trying to acquire the lock.
int waitTime = lockQueue ? Timeout.Infinite : 0;

Queue<EventArgs> fredEventQueueCopy = null;

if(System.Threading.Monitor.TryEnter(fredEventQueueLocker, waitTime))
{
    try
    {
        if(fredEventQueue.Count > 0)
        {
            fredEventQueueCopy = fredEventQueue;
            fredEventQueue = new Queue<EventArgs>();
        }
    }
    finally
    {
        System.Threading.Monitor.Exit(fredEventQueueLocker);
    }
}

All access elsewhere in the code to 'fredEventQueue' is simply 'locked'; in fact, if I replace the above code with the below, RS 9.x does not flag this warning:

// The wait time determines if we block on trying to acquire the lock.
int waitTime = lockQueue ? Timeout.Infinite : 0;
Queue<EventArgs> fredEventQueueCopy = null;

lock(fredEventQueueLocker)
{
    if(fredEventQueue.Count > 0)
    {
        fredEventQueueCopy = fredEventQueue;
        fredEventQueue = new Queue<EventArgs>();
    }
}

Any ideas why RS 9.x is throwing this new inspection warning?

like image 847
SoConfused Avatar asked Dec 28 '25 19:12

SoConfused


1 Answers

Seems like ReSharper doesn't interpret Monitor.TryEnter/Monitor.Exit pattern equals to lock statement. For me it seems like a false positive.

And in fact this is RSRP-441222 which is reported as being fixed in 9.2.

like image 66
Alex Sedow Avatar answered Dec 30 '25 09:12

Alex Sedow