gpt4 book ai didi

c# - 在 IIS 中,System.Random.NextBytes 占用大量 CPU

转载 作者:行者123 更新时间:2023-11-30 16:38:21 24 4
gpt4 key购买 nike

今天,我的 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;
}
}
}

谁能告诉我,是什么导致了这个错误?请注意,这只发生过一次。

最佳答案

可能是因为您正在跨线程共享相同的 Random 实例,所以您在 random 类中遇到了问题,如 here 所述它可能会卡住返回零。随机不是线程安全的。

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

关于c# - 在 IIS 中,System.Random.NextBytes 占用大量 CPU,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55274210/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com