gpt4 book ai didi

asp.net-mvc - unity and Random "Index was outside the bounds of the array"异常

转载 作者:行者123 更新时间:2023-12-04 23:00:53 37 4
gpt4 key购买 nike

我们正在运行的网站有大约 15.000 个实时用户(谷歌分析)(大约 1000 个请求/秒(性能计数器))。

我们在负载均衡器后面有两个 Web 服务器。

有时每天有时每周 1 次我们的 Web 服务器之一停止执行请求并开始响应错误,并且每个请求都记录以下异常:
“System.IndexOutOfRangeException - 索引超出了数组的范围。”

我们的环境:IIS 8.5、.Net 4.5.0、Mvc 5.1.0、Unity 3.5(与 3.0 状态相同)、WebActivatorEx 2.0
在 IIS 中,工作进程 1 和其他设置为默认值。

我们无法捕捉到任何导致此错误的特定场景。应用程序池回收后一切都没有问题。在每个请求都以错误响应之前,没有任何与之相关的错误。

过去与相关的旧 Unity 版本有一个问题:
https://unity.codeplex.com/discussions/328841
http://unity.codeplex.com/workitem/11791
看不出我能做些什么。

这里异常详细信息:

System.IndexOutOfRangeException
Index was outside the bounds of the array.

System.IndexOutOfRangeException: Index was outside the bounds of the array.
at System.Collections.Generic.List`1.Enumerator.MoveNext()
at System.Linq.Enumerable.WhereListIterator`1.MoveNext()
at System.Collections.Generic.List`1..ctor(IEnumerable`1 collection)
at System.Linq.Enumerable.ToList[TSource](IEnumerable`1 source)
at Microsoft.Practices.Unity.NamedTypesRegistry.RegisterType(Type t, String name)
at Microsoft.Practices.Unity.UnityDefaultBehaviorExtension.OnRegisterInstance(Object sender, RegisterInstanceEventArgs e)
at System.EventHandler`1.Invoke(Object sender, TEventArgs e)
at Microsoft.Practices.Unity.UnityContainer.RegisterInstance(Type t, String name, Object instance, LifetimeManager lifetime)
at Microsoft.Practices.Unity.UnityContainerExtensions.RegisterInstance[TInterface](IUnityContainer container, TInterface instance, LifetimeManager lifetimeManager)
at DemoSite.News.Portal.UI.App_Start.UnityConfig.<>c__DisplayClass1.<RegisterTypes>b__0()
at DemoSite.News.Portal.Core.Controller.BaseController.Initialize(RequestContext requestContext)
at System.Web.Mvc.Controller.BeginExecute(RequestContext requestContext, AsyncCallback callback, Object state)
at System.Web.Mvc.MvcHandler.<BeginProcessRequest>b__4(AsyncCallback asyncCallback, Object asyncState, ProcessRequestState innerState)
at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncVoid`1.CallBeginDelegate(AsyncCallback callback, Object callbackState)
at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResultBase`1.Begin(AsyncCallback callback, Object state, Int32 timeout)
at System.Web.Mvc.Async.AsyncResultWrapper.Begin[TState](AsyncCallback callback, Object callbackState, BeginInvokeDelegate`1 beginDelegate, EndInvokeVoidDelegate`1 endDelegate, TState invokeState, Object tag, Int32 timeout, SynchronizationContext callbackSyncContext)
at System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContextBase httpContext, AsyncCallback callback, Object state)
at System.Web.HttpApplication.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()
at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously)

我的配置如下:
public static void RegisterTypes(IUnityContainer container) 
{
var section = (UnityConfigurationSection)ConfigurationManager.GetSection("unity");
container.LoadConfiguration(section);
ServiceLocator.SetLocatorProvider(() => new UnityServiceLocator(container));
}

初始化方法如下:
protected override void Initialize(System.Web.Routing.RequestContext requestContext)
{
if (requestContext.RouteData.Values["ViewActionId"] != null)
{
int viewActionId;
if (!int.TryParse(requestContext.RouteData.Values["ViewActionId"].ToString(), out viewActionId))
return;

var cacheProvider = ServiceLocator.Current.GetInstance<ICacheProvider>();
List<ViewActionClass> viewActionClasses = null;
string cacheKey = CacheKeyCompute.ComputeCacheKey("ViewActionClass", CacheKeyTypes.DataCache,
new KeyValuePair<string, string>("viewActionId", viewActionId.ToString()));

_configuration = ServiceLocator.Current.GetInstance<IConfiguration>();

viewActionClasses =
cacheProvider.AddOrGetExistingWithLock<List<ViewActionClass>>(cacheKey, () =>
{
var viewActionClassBusiness =
ServiceLocator.Current.GetInstance<IViewActionClassBusiness>();

return viewActionClassBusiness.ViewActionClassGetByViewActionId(viewActionId);
});

ViewBag.ActionClass = viewActionClasses;
ViewBag.Configuration = _configuration;
}
base.Initialize(requestContext);
}

ICacheProvider、IConfiguration 和 IViewActionClassBusiness 的注册 xml
<type type="DemoSite.Runtime.Caching.ICacheProvider, DemoSite.Core"
mapTo="DemoSite.Runtime.Caching.ObjectCacheProvider, DemoSite.Core">
<lifetime type="containerControlledLifetimeManager" />
</type>
<type type="DemoSite.Core.Configuration.IConfiguration, DemoSite.Core"
mapTo="DemoSite.Core.Configuration.ConfigFileConfiguration, DemoSite.Core">
<lifetime type="containerControlledLifetimeManager" />
</type>
<type type="DemoSite.News.Business.IViewActionClassBusiness, DemoSite.News.Business"
mapTo="DemoSite.News.Business.Default.ViewActionClassBusiness, DemoSite.News.Business.Default">
<lifetime type="perRequestLifetimeManager" />
</type>

也许它与高流量有关。
有没有人遇到这样的问题和任何解决方案?

提前致谢

最佳答案

据我从堆栈跟踪中可以看出,您正在 Web 请求期间在容器中注册实例。 RegisterTypeRegisterInstance方法是不是 Unity 中的线程安全(这可能适用于 .NET 中的大多数 DI 库)。这就解释了为什么这种情况会发生在随机点和高负载下。

最好只在启动时注册您的容器,以后不要更改它。特别是使用依赖倒置原则和依赖注入(inject)模式,您尝试集中了解对象图如何连接的知识,但稍后通过进行新的注册再次分散它。即使注册在 Unity 中是线程安全的,您仍然很可能通过在运行时更改注册来引入竞争条件。

更新

您的代码具有导致问题的以下代码:

ServiceLocator.SetLocatorProvider(() => new UnityServiceLocator(container));

这看起来很无辜,但实际上它导致了 并发错误 内存泄漏 .

因为 new语句在 lambda 内,它将导致新的 UnityServiceLocator每次调用 ServiceLocator.Current 时都会创建.这本身并不坏,但是 UnityServiceLocator的构造函数调用 container.RegisterInstance在容器中注册自己。但正如我已经说过的:调用 RegisterInstance` 不是线程安全的。

但即使它是线程安全的,它仍然会导致应用程序中的内存泄漏,因为调用 RegisterInstance不会替换现有注册,但会将其附加到注册列表中。这意味着 UnityServiceLocator 的列表容器中的实例将不断增长,并最终导致系统因 OutOfMemoryException 而崩溃。您实际上很幸运,您首先遇到了这个并发错误,因为 OOM 错误更难追溯。

修复其实很简单:移动 UnityServiceLocator 的构造退出 lambda 并每次返回该单个实例:
var locator = new UnityServiceLocator(container);
ServiceLocator.SetLocatorProvider(() => locator);
UnityServiceLocator 的行为在我看来是一个设计缺陷,因为 RegisterInstance不是线程安全的, UnityServiceLocator不知道它被创建了多少次,它不应该调用 RegisterInstance从它的构造函数中 - 或者至少 - 不检查注册该实例是否安全。

然而问题是删除对 RegisterInstance 的调用是一个突破性的变化,但仍然可能是 Unity 团队的最佳解决方案。大多数用户可能不会注意到丢失的 IServiceLocator无论如何注册,如果他们这样做,Unity 将在这种情况下传达明确的异常消息。另一种选择是让 UnityServiceLocator检查是否已经从容器中解析了任何实例,在这种情况下,从 UnityServiceLocator 中抛出 InvalidOperationException。的构造函数。

关于asp.net-mvc - unity and Random "Index was outside the bounds of the array"异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24822232/

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