Shared Resource – Threading Issue - AuthorizationRulesManager

Shared Resource – Threading Issue - AuthorizationRulesManager

Old forum URL: forums.lhotka.net/forums/t/4616.aspx


Bob Matthew posted on Thursday, April 03, 2008

Rocky,

We’ve been using CSLA since version 2.0 and we’ve been experiencing an issue sporadically since then.  I finally sat down and looked through some logging stack traces to narrow it down.  We’re currently using the RTM of the CSLA 3.5.

We experience the issue typically during a deployment of our web application where the an initial web request gets the CLR to go through and execute the code for the first time, which always takes longer than subsequent requests.  Because our website has a decent amount of traffic, it’s not unusual for multiple people to be requesting from the server simultaneously.

Here’s the call stack:
System.ArgumentException: An item with the same key has already been added.
   at System.ThrowHelper.ThrowArgumentException(ExceptionResource resource)
   at System.Collections.Generic.Dictionary`2.Insert(TKey key, TValue value, Boolean add)
   at Csla.Security.AuthorizationRulesManager.GetRolesForProperty(String propertyName)
   at Csla.Security.AuthorizationRules.HasWriteAllowedRoles(String propertyName)
   at Csla.Core.BusinessBase.CanWriteProperty(String propertyName)
   at Csla.Core.BusinessBase.CanWriteProperty(String propertyName, Boolean throwOnFalse)
   at Csla.Core.BusinessBase.SetProperty[P](PropertyInfo`1 propertyInfo, P newValue, NoAccessBehavior noAccess)
   at Csla.Core.BusinessBase.SetProperty[P](PropertyInfo`1 propertyInfo, P newValue)
   at MyCustomClass.SomeMethod() in ...

The issue occurs on line 34 of the AuthorizationRulesManager.cs file, but it may not be readily apparent on that level.  One level up on line 422 of AuthorizationRules.cs the code calls:

 TypeRules.GetRolesForProperty(propertyName)

Here’s what happens.  Two threads access the code independently.  They get to type RulesList dictionary at the same time and both try to add the same key at the same time (again this is during the web app’s first request), hence the ArgumentException.

I would suggest having a static “lock” or “sync” object (of type Object) in the AuthorizationRulesManager.cs and then performing a “lock(_sync) { … }” on it during the dictionary add.

Great job on 3.5! – We’ve actually had it in production since early February because the code base is incredibly stable.  Thanks again for a great framework.

RockfordLhotka replied on Friday, April 04, 2008

Thank you for the help finding/troubleshooting this problem, I'll take a look at it as soon as I get a chance.

admin replied on Tuesday, May 27, 2008

I have put a (probable) fix into AuthorizationRulesManager in svn. Can you take a look and see if you agree that it will resolve the issue?

Copyright (c) Marimer LLC