My question is, do I need to worry about the static _cachedResult still being seen as null by other threads due to optimizations or other thread caching.
Yes, you do. That's one of the primary reasons volatile
exists.
And it's worth mentioning that uncontested locks add an entirely negligible performance cost, so there's really no reason to just to just lock
the null check and resource generation, as it's almost certainly not going to cause any performance problems, and makes the program much easier to reason about.
And the best solution is to avoid the question entirely and use a higher level of abstraction that is specifically designed to solve the exact problem that you have. In this case, that means Lazy
. You can create a Lazy
object that defines how to create your expensive resource, access it wherever you need the object, and the Lazy
implementation becomes responsible for ensuring that the resource is created no more than once, and that it is properly exposed to the code asking for said resource, and that it is handled efficiently.