Tuesday, August 10, 2010

Thread Safety in MSDN

Just what exactly is the point of even having a ‘thread safety’ comment in the MSDN doco, if it’s just blatant boiler-plate drivel.

Take, for example, System.Text.ASCIIEncoding. Generally speaking there’s only one of these in play at any one time, because the Encoding.ASCII static property is a singleton (as they all are):

public static Encoding ASCII
if (asciiEncoding == null)
asciiEncoding = new ASCIIEncoding();
return asciiEncoding;

So you’d better damn well hope it’s thread safe, otherwise all those concurrent write operations you’re doing, they’re screwed, right? But what does MSDN have to say on the subject:

“Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.”

Oh. Really helpful. Thanks a bunch.

Looking at the usage patterns through the Framework Class Libraries, it’s pretty clear they are thread-safe. Encoding.GetEncoding(int) hands out references to the singletons, which are similarly used with gay abandon in System.IO.Ports.SerialPort, System.IO.File.ReadAllLines, various StreamReader overloads etc… (though BinaryReader chooses to new up its UTF8Encoding, heaven knows why). And the sky would have fallen by now if these usages weren’t at least largely correct.

But poking about in Reflector is clearly not a substitute for accurate documentation, and the ‘parallel processing revolution’ everyone keeps going on about is clearly not going to work if we just keep trotting out the ‘instances members are not guaranteed to be thread safe’ line.

System.Text.Encodings: believed to be thread-safe.

No comments:

Popular Posts