Saturday 14 March 2015

Resharper inspecting consistent locking of objects

Resharper has got a great inspection of your code of many different aspects, such as consistent locking of objects. An example is shown below, I have been using Resharper 9.

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace InconsistentLocking
{
    class Program
    {

        private static readonly object Locker = new object();


        private static readonly List<object> fooness = new List<object>(); 

        static void Main(string[] args)
        {

            DoSomeFoo(); 

        }

        private static void DoSomeFoo()
        {
            lock (Locker)
            {
                fooness.Add("Foo");
            }

            lock (Locker)
            {
                fooness.Remove("Foo");
            }

            lock (Locker)
            {
                fooness.Add("Baze");
            }

            //Resharper warning next - The field is sometimes used inside synchronized block and sometimes without synchronization 

            fooness.Remove("Baze");

            lock (Locker)
            {
                foreach (var foo in fooness)
                {
                    Debug.WriteLine(foo.ToString());
                }
            }


        }

    }
}

The code shows a simple example of using the list called fooness. The warning shows that for the line fooness.Remove("Baze"); that one is not locking the resource, in this case a list in memory called fooness. To fix the warning, just hit Alt+Enter Resharper Shortcut and the code will surround the resource with the lock block again.