Search code examples
.netmultithreadingxslcompiledtransform

XslCompiledTransform thread safety


MSDN for .NET System.Xml.Xsl.XslCompiledTransform Class states:

Thread Safety

[1] The XslCompiledTransform object is thread safe once it has been loaded. In other words, after the Load method has successfully completed, the Transform method can be called simultaneously from multiple threads.

[2] If the Load method is called again in one thread while the Transform method is being called in another thread, the XslCompiledTransform object finishes executing the Transform call by continuing to use the old state. The new state is used when the Load method successfully completes.

[3] Note The Load method is not thread safe when called simultaneously from multiple threads.

I am (fairly) sure that paragraphs [1] & [2] are referring to Load()/Transform() being called (in multiple threads) on the same XslCompiledTransform object instance. But for [3], does anyone know whether they mean simultaneous Load()s on the same instance, or whether (there is something static which means that) you must mutually exclude concurrent Load()s from all instances?


Solution

  • Looking at the code in ILSpy there is no visible static synchronization construct. You can call Load() on different instances from different threads.

    Predictably, Load will instanciate a XSLT compiler and compile the stylesheet to an internal object that will later be used by the Transform methods. That explains [1]: once the transform has been compiled it can be called from different threads as the internal object is now read-only.

    Calling Load again will recompile the internal object so it must be synchronized with any Transform currently going, that accounts for [2].

    Calling the compiler simultaneously from different threads would create a race to build the final internal transform object ([3]). Different instance are independent though, they all have their own internal transform object and they instanciate a new compiler each time Load is called.