为什么不要使用"同步块"自动减少?

时间:2017-06-26 08:28:14

标签: c# .net locking

下面的示例代码分配了大量的同步块。这将在性能监视器中显示为"正在使用的接收器块#34;。但是在释放锁之后,计数器不会减少,直到我手动调用GC.Collect()。为什么这不是自动发生的,或者这不是一个问题?

using System;
using System.Collections.Generic;
using System.Threading;

namespace locktest
{
    public class Program
    {
        static void Main(string[] args)
        {
            var list1 = new List<Object>();
            int threadcount = 0;
            const int maxthreads = 9000;

            for (int i = 0; i < maxthreads; i++)
            {
                var obj = new Object();
                list1.Add(obj);
                Monitor.Enter(obj); // this will initially use just a thin lock
                // lock from a different thread to move to the sync blocks table
                ThreadPool.QueueUserWorkItem(o =>
                {
                    Monitor.TryEnter(o, 1);
                    Interlocked.Increment(ref threadcount);
                }, obj);
            }

            while (threadcount < maxthreads)
                Thread.Sleep(100); // wait until all threads have been finished

            foreach (var obj in list1)
                Monitor.Exit(obj); // release the locks
            list1.Clear();

            Console.WriteLine("Press enter to force GC.");
            Console.ReadKey();
            GC.Collect(); // this will reduce the number of sync blocks to almost 0
            Console.WriteLine("Press enter to quit.");
            Console.ReadKey();
        }
    }
}

相关:What is a “Sync Block” and tips for reducing the count

0 个答案:

没有答案