C# · 12月 22, 2021

c# – 如何组合ThreadLocal变量的值?

我遇到过.NET4的ThreadLocal< T>并且想知道是否有办法累积所有线程的.Value值.

在Microsoft的ppl C库中,它们有Concurrency::combinable::combine_each,.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));}解决方法 从.Net 4.5开始,microsoft在ThreadLocal类中添加了一个名为Values的属性,可以完全满足您的需求.请在下面找到它的工作方式: var localResult = new ThreadLocal<int>(() => 0,trackAllValues: true);Parallel.For(0,10000,i =>{ localResult.Value += Compute(i);});int result = localResult.Values.Sum();

上面的代码是从博客文章http://blogs.msdn.com/b/pfxteam/archive/2011/11/11/10236000.aspx获得的