How to combine values from the variable ThreadLocal <T>?
I came across .NET4 ThreadLocal<T>
and wondered if there was a way to accumulate .Value
values from all threads.
In the Microsoft ppl C ++ library, they have Concurrency::combinable::combine_each
, is there an equivalent method for .NET 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)); }
Starting with .Net 4.5, microsoft has added the Values
attribute to the ThreadLocal
class, which does exactly what you need. The following describes how this 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 http://blogs.msdn.com/b/pfxteam/archive/2011/11/11/10236000.aspx
This information is not available. 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 guidance on how to write a wrapper.