C# – Standard Attributes for Thread Safety and Immutability

c

Except for a blog post here and there, describing the custom attributes someone created, but that do not seem to get any traction – like one describing how to enforce immutability, another one on Documenting Thread Safety, modeling the attributes after JCIP annotations – is there any standard emerging? Anything MS might be planning for the future?

This is something that should be standard, if there's to be any chance of interoperability between libraries concurrency-wise. Both for documentation purposes, and also to feed static / dynamic test tools.

If MS isn't doing anything in that direction, it could be done on CodePlex – but I couldn't find anything there, either.

<opinion>Concurrency and thread safety are really hard in imperative and object-languages like C# and Java, we should try to tame it, until we hopefully switch to more appropriate languages.</opinion>

Best Answer

The problem with both immutability and thread safety are that they are not black and white concepts, but there are a number of possible guarantees in that regard. Reducing that to simple attributes might be hard. IMO a simple ThreadSafe and Immutable attribute isn't enough. Still working out a set of attributes capturing at least the most important semantics sounds promising to me.

For example take an AddRange method. It might be thread safe enough to never corrupt the state of the underlying collection, but might not be atomic. A common implementation with these properties might be just calling an atomic Add method for each element.

On the immutability side we have different aspects too:

  • Offering only readonly accessors or truly never changing
  • Depth of immutability i.e. are sub-objects immutable too
  • Physical vs. logical immutability. For example lazy initialization does not change the visible state, but changes the internal state.

One annotation is this context already exists: Pure for side effect free methods.