在IIS中,System.Random.NextBytes占用了很高的CPU使用率

时间:2019-03-21 05:19:54

标签: c#

今天,我的IIS站点占用了繁忙的CPU,我的服务器运行非常缓慢! 然后我从任务管理器中转储,然后执行IISReset,问题解决了。

在windbg中,我使用!runaway查找长时间执行的线程,例如: enter image description here

并使用!clrstack找出执行该代码的前10个线程: System.Random.NextBytes(Byte [])),例如:

Thread  30
Current frame: (MethodDesc 00007ffb5252c418 +0x20 System.Random.InternalSample())
Child-SP         RetAddr          Caller, Callee
000000487470b460 00007ffb531d8138 (MethodDesc 00007ffb5252c458 +0x28 System.Random.NextBytes(Byte[]))
000000487470b4b0 00007ffaffafe87a (MethodDesc 00007ffafeeb4e20 +0x4a Pinpoint.Core.Util.SpanIdUtil.GetNewSpanId())
000000487470b4e0 00007ffb014a53fb (MethodDesc 00007ffafeeb4e30 +0x1b Pinpoint.Core.Util.SpanIdUtil.GetNextSpanId(Int64, Int64))
000000487470b520 00007ffb014a5370 (MethodDesc 00007ffafeeb4150 +0x30 Pinpoint.Core.TraceId.GetNextTraceId())
000000487470b5a0 00007ffaffae4dab (MethodDesc 00007ffaff317ed0 +0x1cb Mike.Pinpoint.Plugin.WebRequestPlugins.TraceHttpWebRequest.BeforeGetResponse(System.Net.HttpWebRequest))
000000487470bbb0 00007ffb529444e0 (MethodDesc 00007ffb52535888 +0x80 System.Reflection.RuntimeMethodInfo.UnsafeInvokeInternal(System.Object, System.Object[], System.Object[]))
000000487470bcf0 00007ffb529444e0 (MethodDesc 00007ffb52535888 +0x80 System.Reflection.RuntimeMethodInfo.UnsafeInvokeInternal(System.Object, System.Object[], System.Object[]))
000000487470bd60 00007ffb5292f4ee (MethodDesc 00007ffb52535870 +0x8e System.Reflection.RuntimeMethodInfo.Invoke(System.Object, System.Reflection.BindingFlags, System.Reflection.Binder, System.Object[], System.Globalization.CultureInfo))
000000487470bde0 00007ffaffae4b79 (MethodDesc 00007ffaff318238 +0x99 Mike.Pinpoint.Plugin.WebRequestPlugins.TraceFilterImpl.BeforeGetResponseForFilter(System.Net.HttpWebRequest))
000000487470bdf0 00007ffb528f93e0 (MethodDesc 00007ffb526b1270 +0x120 System.IO.StreamWriter.Dispose(Boolean))

这是我的原始代码:

using System;

namespace Pinpoint.Core.Util
{
    public class SpanIdUtil
    {
        private static readonly Random rnd = new Random(Environment.TickCount);
        public const long Null = -1;

        public static long GetNewSpanId()
        {
            byte[] buf = new byte[8];
            rnd.NextBytes(buf);
            long newId = BitConverter.ToInt64(buf, 0);
            return newId;
        }

        public static long GetNextSpanId(long spanId, long parentSpanId)
        {
            long newId = GetNewSpanId();

            while (newId == spanId || newId == parentSpanId)
            {
                newId = GetNewSpanId();
            }
            return newId;
        }
    }
}

有人可以告诉我,是什么导致了此错误? 请注意,这只发生过一次。

1 个答案:

答案 0 :(得分:2)

就像您在线程中共享Random的相同实例一样,您在here描述的随机类内部遇到了一个问题,该问题可能会卡住返回零。随机不是线程安全的。

就个人而言,在服务器应用程序上,我永远不会使用没有保护倒计时的while循环,如果该保护倒计数到零,则抛出异常。除非您能(从数学上)证明循环将完成,否则应防止循环卡住,因为在服务器应用程序中,一旦停止,您将永远失去线程。