Search code examples
c#visual-studiovisual-studio-2012auto-indent

How to acquire multiple locks in VS2012 without messing up indentation


This looks like a silly question, but I'm not able to find a solution to this.

My problem is that C# doesn't allow for the acquisition of multiple locks in a single lock statement. This won't work:

lock (a, b, c, d)
{
    // ...
}

Instead, it seems to require an insane amount of indentation in order to do this:

lock (a)
    lock (b)
        lock (c)
            lock (d)
            {
                // ...
            }

Coupled with all other indentation levels that the code is already in (namespaces, class, method, conditionals, loops, ...), this gets insane. So instead, I want to use this formatting:

lock (a) lock (b) lock (c) lock (d)
{
    // ...
}

and preserve my sanity. But Visual Studio (I'm using 2012) won't hear of it. As soon as I enter any closing brace, the above is transformed to something silly, like:

lock (a) lock (b) lock (c) lock (d)
                  {
                      // ...
                  }

And there seems there's nothing I can do. Is there any way to make this work?


Solution

  • Using that many locks at a time is just asking for deadlock. Heck, even acquiring two different locks at a time runs that risk.

    At the very least, you should be very very careful to only ever take these locks in exactly the same order everywhere that more than one is acquired at a time.

    Also, "nice formatting" is in the eye of the beholder. That is, everyone's got their own idea of what's best. But, the following should work, without VS messing with it unless you specifically ask it to (e.g. by triggering an auto-format rule or explicitly auto-formatting):

    lock (a)
    lock (b)
    lock (c)
    lock (d)
    {
    }
    

    You can also use this approach with using statements (where it's much more common to have more than one in a row), where the VS IDE already anticipates it.