I use a static ThreadLocal to cache some heavyweight objects. Consider the following code:
class MatchItemFinder
{
private static ThreadLocal<PaddedImage> tempImage;
MatchItemFinder()
{
if(tempImage==null)
tempImage = new ThreadLocal<PaddedImage>(
() => new PaddedImage(patchSize, patchSize));
}
internal void DoSomething(){
//Do something with tempImage.Value
}
}
When DoSomething() is called from multiple Task Parallel Library threads, when each instance is created? I mean obviously threads are reused so is my tempImage created every time a thread is created or every time a thread is reused?
With a design perspective do you think this kind of caching would be a great decision or there are better strategies to cache large objects in a thread safe manner?
I'm using .Net 4.