How to combine all values from a ThreadLocal<T>?
.net, .net-4.0, c#, multithreading
Solution
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
Problem
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)); } ```