I've run across .NET 4's ThreadLocal<T>
and was wondering if there's a way to accumulate the .Value
values from all threads.
In Microsoft's ppl C++ library they have Concurrency::combinable::combine_each
, is there an equivalent method for .NET's ThreadLocal
?
ThreadLocal<long> ticks = new ThreadLocal<long>();
void AddTicks(StopWatch sw)
{
ticks.Value += sw.ElapsedTicks;
}
void ReportTimes()
{
long totalTicks = /* How do I accumulate all the different values? */;
Console.WriteLine(TimeSpan.FromTicks(totalTicks));
}
The ThreadLocal class is used to create thread local variables which can only be read and written by the same thread. For example, if two threads are accessing code having reference to same threadLocal variable then each thread will not see any modification to threadLocal variable done by other thread.
Java ThreadLocal is used to create thread local variables. We know that all threads of an Object share it's variables, so the variable is not thread safe. We can use synchronization for thread safety but if we want to avoid synchronization, we can use ThreadLocal variables.
Thread-local storage (TLS) is a computer programming method that uses static or global memory local to a thread. All threads of a process share the virtual address space of the process. The local variables of a function are unique to each thread that runs the function.
static final ThreadLocal variables are thread safe. static makes the ThreadLocal variable available across multiple classes for the respective thread only. it's a kind of Global variable decaration of the respective thread local variables across multiple classes.
Since .NET 4.5, Microsoft added an attribute called Values
to the ThreadLocal
class that does exactly what you need. Here's the way it works:
var localResult = new ThreadLocal<int>(() => 0, trackAllValues: true);
Parallel.For(0, 10000, i =>
{
localResult.Value += Compute(i);
});
int result = localResult.Values.Sum();
The code above was obtained from the blog post: New in .NET 4.5: ThreadLocal.Values
This information is not available in .NET 4.0. For 4.5 and up, see Joao's answer.
Microsoft is considering adding such a feature. You will need to write a wrapper around ThreadLocal<T>
to add this behavior.
Here is a blog post that gives some directions about how to write a wrapper.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With