ÆäËüÍøÂçÏà¹Ø×é¼þÒ²½«µÃµ½½øÒ»²½ÓÅ»¯¡£ÀýÈçSslStreamͨ³£½«Î§ÈÆÔÚNetworkStreamÖУ¬ÒÔ±ãÏòÁ¬½ÓÖÐÌí¼ÓSSL¡£ÏÂÃæµÄʾÀý½«¿´µ½ÕâÖÖÓ°Ï죬Õâ¸öʾÀý½«ÔÚNetworkStreamÖ®ÉÏÌí¼ÓSslStreamµÄÓ÷¨£º
using System; using System.Diagnostics; using System.Threading; class Test { static void Main() { while (true) { int remaining = 20_000_000; var mres = new ManualResetEventSlim(); WaitCallback wc = null; wc = delegate { if (Interlocked.Decrement(ref remaining) <= 0) mres.Set(); else ThreadPool.QueueUserWorkItem(wc); }; var sw = new Stopwatch(); int gen0 = GC.CollectionCount(0), gen1 = GC.CollectionCount(1), gen2 = GC.CollectionCount(2); sw.Start(); for (int i = 0; i < Environment.ProcessorCount; i++) ThreadPool.QueueUserWorkItem(wc); mres.Wait(); Console.WriteLine($); } } }
ÔÚ.NET 4.7ÖУ¬»áµÃµ½ÈçϽá¹û£º
Elapsed=00:00:21.1171962 Gen0=470 Gen1=3 Gen2=1
.NET Core 2.0°üº¬ÁËÖîÈçdotnet / corefx££12935ºÍdotnet / corefx££13274µÈPRµÄ¸Ä½ø£¬ÕâÁ½Õ߶¼½«´ó´ó¼õÉÙÁËʹÓÃSslStreamËùÉæ¼°µÄ·ÖÅä¡£ÔÚ.NET Core 2.0ÉÏÔËÐÐÏàͬµÄ´úÂëʱ£¬»áµÃµ½ÈçϽá¹û£º
Elapsed=00:00:05.6456073 Gen0=74 Gen1=0 Gen2=0
85£¥µÄÀ¬»øÊÕ¼¯Òѱ»É¾³ý£¡
²¢·¢
¶ÔÓÚ²¢·¢ºÍ²¢ÐÐÐÔÏà¹ØµÄÔʼ»¯ºÍ»ù´¡²¿·Ö£¬Ò²µÃµ½ÁËÐí¶à¸Ä½ø¡£
ÕâÀïµÄÒ»¸ö¹Ø¼üµãÊÇThreadPool£¬ËüÊÇÖ´ÐÐÐí¶à.NETÓ¦ÓóÌÐòµÄºËÐÄ¡£ÀýÈ磬PR dotnet / coreclr££3157¼õÉÙÁËQueueUserWorkItemÖÐÉæ¼°µÄijЩ¶ÔÏóµÄ´óС£¬PR dotnet / coreclr££9234ʹÓÃÁËConcurrentQueue <T>ÖØдÀ´Ìæ»»ThreadPoolµÄÈ«¾Ö¶ÓÁУ¬ÆäÖлáÓõ½½ÏÉÙµÄͬ²½ºÍ·ÖÅä¡£´ÓÒÔϵÄʾÀýÖУ¬»á¿´µ½×îÖÕ½á¹û£º
using System; using System.Diagnostics; using System.Threading; class Test { static void Main() { while (true) { int remaining = 20_000_000; var mres = new ManualResetEventSlim(); WaitCallback wc = null; wc = delegate { if (Interlocked.Decrement(ref remaining) <= 0) mres.Set(); else ThreadPool.QueueUserWorkItem(wc); }; var sw = new Stopwatch(); int gen0 = GC.CollectionCount(0), gen1 = GC.CollectionCount(1), gen2 = GC.CollectionCount(2); sw.Start(); for (int i = 0; i < Environment.ProcessorCount; i++) ThreadPool.QueueUserWorkItem(wc); mres.Wait(); Console.WriteLine($); } } }
ÔÚ.NET 4.7ÖУ¬»áµÈµ½ÈçϽá¹û£º
Elapsed=00:00:03.6263995 Gen0=225 Gen1=51 Gen2=16 Elapsed=00:00:03.6304345 Gen0=231 Gen1=62 Gen2=17 Elapsed=00:00:03.6142323 Gen0=225 Gen1=53 Gen2=16 Elapsed=00:00:03.6565384 Gen0=232 Gen1=62 Gen2=16 Elapsed=00:00:03.5999892 Gen0=228 Gen1=62 Gen2=17
¶øÔÚ.NET Core 2.0ÖУ¬»áµÃµ½ÈçϽá¹û£º
Elapsed=00:00:02.1797508 Gen0=153 Gen1=0 Gen2=0 Elapsed=00:00:02.1188833 Gen0=154 Gen1=0 Gen2=0 Elapsed=00:00:02.1000003 Gen0=153 Gen1=0 Gen2=0 Elapsed=00:00:02.1024852 Gen0=153 Gen1=0 Gen2=0 Elapsed=00:00:02.1044461 Gen0=154 Gen1=1 Gen2=0
ÕâÊÇÒ»¸ö¾Þ´óµÄÍÌÍÂÁ¿µÄ¸ÄÉÆ£¬²¢ÇÒÕâÑùÒ»¸öºËÐÄ×é¼þµÄÀ¬»øÁ¿Ò²½«´ó·ù¼õÉÙ¡£
¡¡