Reputation: 1619
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.
Upvotes: 0
Views: 580
Reputation: 171236
Thread local variables do not cooperate with the TPL or with the thread pool. They are Thread
-based. When any TPL library function reuses a thread your thread locals will be 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?
If your cache items are immutable there is no need for thread local items. Use a global cache.
Upvotes: 2