Reputation: 237
The simplified code below is for illustration. Class1 creates a dynamic static object dynamObj based on JSON stream from the back end. A locker is used when updating dynamObj. Then Class2 takes that dynamObj for further processing, but sometimes (not always) an index out-of-range exception is triggered when looping through the array-based properties of dynamObj. Here is the question:
In Class2, whenever Method2(dynamObjCopy) is called and is in execution, will dynamObjCopy parameter be updated automatically, if the original static dynamObj is updated? In other words, can the Length of PropertyArray change while the while loop is in execution? If this is the case and the reason for out of range exception, how do I lock the Method2 parameter dynamObjCopy to prevent it from updating? Would it work if I locked the entire body of Method2 similar to what is done in Class1?
public class Class1
{
public static dynamic dynamObj = null;
public static ReaderWriterLockSlim locker = new ReaderWriterLockSlim();
try
{
locker.EnterWriteLock();
dynamObj = deserializedDynamObjFromJSONstream;
}
finally
{
locker.ExitWriteLock();
}
}
public class Class2
{
public dynamic Method1
{
dynamic dynamObjCopy = dynamObj;
Method2(dynamObjCopy);
}
private dynamic Method2(dynamic dynamObjCopy)
{
var ind = 0;
while (ind < dynamObjCopy.PropertyArray.Length)
{// here we get index out-of-range exception. Why?
someList.Add(dynamObjCopy.PropertyArray[ind]);
ind++;
}
}
}
Upvotes: 0
Views: 32