I’ve recently helped a client resolve some interesting issues with their Tridion template building blocks. The issue was that when publishing the first time desired results were produced by the template. However, when publishing many pages, or republishing the same page/component presentation, subsequently produced strange output results.
The logic in our TBB parsed the Output item in the package and made various manipulations to it. I won’t get into the details of that. The issue was due to having static private variables declared within the TBB. These variables were various data structures and primitives manipulated by methods within our ITemplate-inherited class. The methods themselves had to also be declared as static. Â Refactoring the code away from “static” resolved the issue.
Here is why you cannot use static variables in Tridion templates: Â Primarily because they become global shared variables across all publish threads. Â Here is what the Tridion TOM.NET Session and Engine class API states regarding this matter:
IMPORTANT NOTE: Session objects are not thread-safe; you must not share Session objects across threads. Furthermore, the thread that creates a Session object should be in a Single Threaded Apartment (STA), since the Session will internally create an Apartment Threaded COM object. See SetApartmentState(ApartmentState).Â
The Tridion Session object, which the Engine uses (or, as the docs put it, “aggregates”) subscribes to the Single Threaded Apartment model (STA).
An STA is basically a model where the server controls the threads, and each individual thread must not spin off additional sub-threads that depend on the STA-controlled objects. So in our case: the Tridion CM is the server that spins off and controls threads (e.g. we can publish many items simultaneously), and each template is executed within it’s own thread. So if we develop a template that spins of other threads, the common memory across threads, i.e. static variables, isn’t managed. Â So STA threads can overwrite each other.
Here is a snippet from an article explaining STAs in much more detail:
…all access to global variables and functions of the server will need to be serialized properly because more than one object may try to access these from different threads. This rule also applies to class static variables and functions. [http://www.codeproject.com/Articles/9190/Understanding-The-COM-Single-Threaded-Apartment-Pa]
So in a common scenario, when is it appropriate to use “static” within a TBB? Well, how about in procedural methods that take some inputs, create new objects, massage them and return them. In other words, if the method is self-contained. A Utility class is a common such scenario.
In conclusion, don’t use static variables inside your TBBs or Event System code.