Unity3D: Return value with a Delegate - c#

I want to be able to get the return values from all the methods in my delegate. This is the code I have written in c#.
using UnityEngine;
using System.Collections;
public static class DelagetsAndEvents {
public delegate int UnitEventHandler(string _unit);
public static event UnitEventHandler unitSpawn;
public static int UnitSpawn(string _unit)
{
if(unitSpawn != null)
{
unitSpawn(_unit);
}
// here I want to return 1 + 2 from Planet/UnitSpawn and SolarSystem/UnitSpawn
// is it possible to run a foreach on every method in the delegate and add their returns?
return (method 1's return value) + (method 2's return value) (Or both seperately, that would be even better)
}
}
public class Planet {
public Planet()
{
DelagetsAndEvents.unitSpawn += UnitSpawn;
}
int UnitSpawn(string _unit)
{
Debug.Log("yo");
return 1;
}
}
public class SolarSystem{
public SolarSystem()
{
DelagetsAndEvents.unitSpawn += UnitSpawn;
}
int UnitSpawn(string _unit)
{
Debug.Log("bla");
return 2;
}
}
As you can see, the delegate has a return type of int. Then the methods I put into my delegate also have the return type of int. One of them return 1 and the other one return 2. Is there a way to get those results to the location where I execute my delegate? That will be here:
using UnityEngine;
using System.Collections;
public class TestDelagets : MonoBehaviour {
void Start () {
SolarSystem s = new SolarSystem();
Planet p = new Planet();
string g = "";
int i = DelagetsAndEvents.UnitSpawn(g);
Debug.Log(i);
}
}

Well, in the "regular" .NET framework, you could use Delegate.GetInvocationList. For example, to combine that with LINQ:
// Note: do all of this after checking that unitSpawn is non-null...
var results = unitSpawn.GetInvocationList()
.Cast<UnitEventHandler>()
.Select(d => d(_unit))
.ToList();
I don't know offhand whether that will work with Unity, but I'd hope it would...
If the LINQ part doesn't work, you could use:
var invocations = unitSpawn.GetInvocationList();
var results = new int[invocations.Length];
for (int i = 0; i < invocations.Length; i++)
{
results[i] = ((UnitEventHandler)invocations[i]).Invoke(_unit);
}

As you mention that you would need to get the added value or the two separate values, I would choose a different approach.
You could use Linq but Unity recommends to avoid it. Most likely due to the process of serialization between C++ and C# and GC.
You could store your methods in an array of actions. Then you can either get the full amount, or one by one with a basic foreach loop.
public class DelegateContainer : IDisposable{
private IList<Func<string, int>> container = null;
public DelegateContainer(){
this.container = new List<Func<string,int>>();
}
public void Dispose(){
this.container.Clear();
this.container = null;
}
public bool AddMethod(Func<string, int> func){
if(func != null && this.container.Contains(func) == false){
this.container.Add(func);
return true;
}
return false;
}
public bool RemoveMethod(Func<string, int>func){
if(func != null && this.container.Contains(func) == true){
this.container.Remove(func);
return true;
}
return false;
}
public int GetFullValue(){
int total = 0;
foreach(var meth in this.container){
if(meth != null) { total += meth(""); }
}
return total;
}
public IEnumerable<int> GetAllValues(){
IList <int> list = new List<int>();
foreach(var meth in this.container){
if(meth != null) { list.Add(meth("");); }
}
return list as IEnumerable<int>;
}
}

Thanks guys! It helped alot. I solved it with the folowing code:
using UnityEngine;
using System.Collections;
public static class DelagetsAndEvents {
public delegate int UnitEventHandler(string _unit);
public static event UnitEventHandler unitSpawn;
public static int[] UnitSpawn(string _unit)
{
if(unitSpawn != null)
{
unitSpawn(_unit);
}
System.Delegate[] funcs = unitSpawn.GetInvocationList();
int[] TIntArray = new int[funcs.Length];
for (int i = 0; i < funcs.Length; ++i)
{
TIntArray[i] = (int) funcs[i].DynamicInvoke(_unit);
}
return TIntArray;
}
}
public class Planet {
public Planet()
{
DelagetsAndEvents.unitSpawn += UnitSpawn;
}
int UnitSpawn(string _unit)
{
Debug.Log("yo");
return 1;
}
}
public class SolarSystem{
public SolarSystem()
{
DelagetsAndEvents.unitSpawn += UnitSpawn;
}
int UnitSpawn(string _unit)
{
Debug.Log("bla");
return 2;
}
}
and:
using UnityEngine;
using System.Collections;
using System.Collections;
public class TestDelagets : MonoBehaviour {
void Start () {
SolarSystem s = new SolarSystem();
Planet p = new Planet();
string g = "";
int[] i = DelagetsAndEvents.UnitSpawn(g);
foreach(int f in i)
{
Debug.Log(f);
}
}
}

Related

How to automate unit testing of object state?

I have this serializable class which is my class for persisting game data.
[Serializable]
class GameData
{
public float experience = Helper.DEFAULT_EXPERIENCE;
public float score = Helper.DEFAULT_SCORE;
public float winPercent = Helper.DEFAULT_WIN_PERCENT;
public int tasksSolved = Helper.DEFAULT_NUM_OF_TASKS_SOLVED;
public int correct = Helper.DEFAULT_NUM_OF_CORRECT;
public int additions = Helper.DEFAULT_NUM_OF_ADDITIONS;
public int subtractions = Helper.DEFAULT_NUM_OF_SUBTRACTIONS;
public bool useAddition = Helper.DEFAULT_USE_ADDITION;
public bool useSubtraction = Helper.DEFAULT_USE_SUBTRACTION;
public bool useIncrementalRange = Helper.DEFAULT_USE_INCREMENTAL_RANGE;
public bool gameStateDirty = Helper.DEFAULT_GAME_STATE_DIRTY;
public bool gameIsNormal = Helper.DEFAULT_GAME_IS_NORMAL;
public bool operandsSign = Helper.DEFAULT_OPERANDS_SIGN;
}
The class that utilizes this serializable class looks like this:
using UnityEngine;
using System;
using System.Runtime.Serialization.Formatters.Binary;
using System.IO;
public class SaveLoadGameData : MonoBehaviour
{
public static SaveLoadGameData gameState;
public float experience = Helper.DEFAULT_EXPERIENCE;
public float score = Helper.DEFAULT_SCORE;
public float winPercent = Helper.DEFAULT_WIN_PERCENT;
public int tasksSolved = Helper.DEFAULT_NUM_OF_TASKS_SOLVED;
public int correct = Helper.DEFAULT_NUM_OF_CORRECT;
public int additions = Helper.DEFAULT_NUM_OF_ADDITIONS;
public int subtractions = Helper.DEFAULT_NUM_OF_SUBTRACTIONS;
public bool useAddition = Helper.DEFAULT_USE_ADDITION;
public bool useSubtraction = Helper.DEFAULT_USE_SUBTRACTION;
public bool useIncrementalRange = Helper.DEFAULT_USE_INCREMENTAL_RANGE;
public bool gameStateDirty = Helper.DEFAULT_GAME_STATE_DIRTY;
public bool gameIsNormal = Helper.DEFAULT_GAME_IS_NORMAL;
public bool operandsSign = Helper.DEFAULT_OPERANDS_SIGN;
void Awake () {}
public void init ()
{
if (gameState == null)
{
DontDestroyOnLoad(gameObject);
gameState = this;
}
else if (gameState != this)
{
Destroy(gameObject);
}
}
public void SaveForWeb ()
{
UpdateGameState();
try
{
PlayerPrefs.SetFloat(Helper.EXP_KEY, experience);
PlayerPrefs.SetFloat(Helper.SCORE_KEY, score);
PlayerPrefs.SetFloat(Helper.WIN_PERCENT_KEY, winPercent);
PlayerPrefs.SetInt(Helper.TASKS_SOLVED_KEY, tasksSolved);
PlayerPrefs.SetInt(Helper.CORRECT_ANSWERS_KEY, correct);
PlayerPrefs.SetInt(Helper.ADDITIONS_KEY, additions);
PlayerPrefs.SetInt(Helper.SUBTRACTIONS_KEY, subtractions);
PlayerPrefs.SetInt(Helper.USE_ADDITION, Helper.BoolToInt(useAddition));
PlayerPrefs.SetInt(Helper.USE_SUBTRACTION, Helper.BoolToInt(useSubtraction));
PlayerPrefs.SetInt(Helper.USE_INCREMENTAL_RANGE, Helper.BoolToInt(useIncrementalRange));
PlayerPrefs.SetInt(Helper.GAME_STATE_DIRTY, Helper.BoolToInt(gameStateDirty));
PlayerPrefs.SetInt(Helper.OPERANDS_SIGN, Helper.BoolToInt(operandsSign));
PlayerPrefs.Save();
}
catch (Exception ex)
{
Debug.Log(ex.Message);
}
}
public void SaveForX86 () {}
public void Load () {}
public void UpdateGameState () {}
public void ResetGameState () {}
}
Note: GameData is inside the same file with SaveLoadGameData class.
As you can see GameData class has ton of stuff and creating test for each function inside SaveLoadGameData class is long and boring process. I have to create a fake object for each property inside GameData and test the functionality of the functions in SaveLoadGameData do they do what they are supposed to do.
Note: This is Unity3D 5 code and testing MonoBehaviors with stubs and mocks is almost immposible. Therefore I created helper function that creates fake object:
SaveLoadGameData saveLoadObject;
GameObject gameStateObject;
SaveLoadGameData CreateFakeSaveLoadObject ()
{
gameStateObject = new GameObject();
saveLoadObject = gameStateObject.AddComponent<SaveLoadGameData>();
saveLoadObject.init();
saveLoadObject.experience = Arg.Is<float>(x => x > 0);
saveLoadObject.score = Arg.Is<float>(x => x > 0);
saveLoadObject.winPercent = 75;
saveLoadObject.tasksSolved = 40;
saveLoadObject.correct = 30;
saveLoadObject.additions = 10;
saveLoadObject.subtractions = 10;
saveLoadObject.useAddition = false;
saveLoadObject.useSubtraction = false;
saveLoadObject.useIncrementalRange = true;
saveLoadObject.gameStateDirty = true;
saveLoadObject.gameIsNormal = false;
saveLoadObject.operandsSign = true;
return saveLoadObject;
}
How would you automate this process?
Yes two asserts inside one test is a bad practice but what would you do instead?
Example test for SaveForWeb()
[Test]
public void SaveForWebTest_CreateFakeGameStateObjectRunTheFunctionAndCheckIfLongestChainKeyExists_PassesIfLongestChainKeyExistsInPlayerPrefs()
{
// arrange
saveLoadObject = CreateFakeSaveLoadObject();
// act
saveLoadObject.SaveForWeb();
// assert
Assert.True(PlayerPrefs.HasKey(Helper.LONGEST_CHAIN_KEY));
Assert.AreEqual(saveLoadObject.longestChain, PlayerPrefs.GetInt(Helper.LONGEST_CHAIN_KEY, Helper.DEFAULT_LONGEST_CHAIN));
GameObject.DestroyImmediate(gameStateObject);
}
Since Helper is static class containing only public constants I had to use BindingFlags.Static and BindingFlags.Public to iterate over its members, so I used this code snippet to automate asserting over several fields of different type:
FieldInfo[] helperFields = typeof(SaveLoadGameData).GetFields();
FieldInfo[] defaults = typeof(Helper).GetFields(BindingFlags.Static | BindingFlags.Public);
for(int i = 0; i < defaults.Length; i += 1)
{
Debug.Log(helperFields[i].Name + ", " + helperFields[i].GetValue(saveLoadObject) + ", " + defaults[i].GetValue(null));
Assert.AreEqual(helperFields[i].GetValue(saveLoadObject), defaults[i].GetValue(null));
}
Note: defaults and helperFields have the same length as I am checking if helperFields have the default values after using ResetGameState().
Though this answer is about ResetGameState() instead of SaveForWeb() function, this code can be applied wherever possible.

Create reference to a primitive type field in class

I have a few classes which have some primitive fields and I would like to create a generalized wrapper for them in order to access their fields. This wrapper should somehow contain a reference to the fields of my classes so that I can read/write the values of these fields. The idea is to create a genralized architecture for these classes so that I dont have to write code for each of them. The classes have fields which have a number in them which will be used as an Id to access the fields.
This is some example code that might shed some light on my requirement. What I want in the end is to change the value of some field in the object of Fancy1 class without accessing the object itself but through its wrapper.
class Fancy1
{
public double level1;
public bool isEnable1;
public double level2;
public bool isEnable2;
public double level3;
}
class Fancy2
{
public double level4;
public bool isEnable4;
public double level6;
public bool isEnable6;
public double level7;
}
class FieldWrapper
{
public int id { get; set; }
public object level { get; set; }
public object isEnabled { get; set; }
public FieldWrapper(int id, object level, object isEnabled)
{
this.id = id;
this.level = level;
this.isEnabled = isEnabled;
}
}
class FancyWrapper
{
private Fancy scn;
public FancyWrapper(Fancy scn)
{
if (!(scn is Fancy))
throw new ArgumentException(scn.GetType().FullName + " is not a supported type!");
this.scn = scn;
}
private Dictionary<int, FieldWrapper> fieldLut = new Dictionary<int, FieldWrapper>();
private List<FieldWrapper> _fields { get { return fieldLut.Values.ToList(); } }
public List<FieldWrapper> fields
{
get
{
if (_fields.Count == 0)
{
foreach (System.Reflection.FieldInfo fieldInfo in scn.GetType().GetFields())
{
if (fieldInfo.FieldType == typeof(double))
{
int satId = getIdNr(fieldInfo.Name);
fieldLut.Add(satId, new FieldWrapper(satId, fieldInfo.GetValue(scn), true));
}
}
foreach (System.Reflection.FieldInfo fieldInfo in scn.GetType().GetFields())
{
if (fieldInfo.FieldType == typeof(bool))
{
int satId = getIdNr(fieldInfo.Name);
fieldLut[satId].isEnabled = fieldInfo.GetValue(scn);
}
}
}
return _fields;
}
}
private int getIdNr(string name)
{
System.Text.RegularExpressions.Match m = System.Text.RegularExpressions.Regex.Match(name, #"\d+");
return Int32.Parse(m.Value);
}
}
class Program
{
static void Main(string[] args)
{
Fancy1 fancy = new Fancy1();
fancy.level1 = 1;
fancy.isEnable1 = true;
fancy.level2 = 2;
fancy.isEnable2 = false;
fancy.level3 = 3;
FancyWrapper wrapper = new FancyWrapper(fancy);
wrapper.fields[2].level = 10;
// fancy.level2 should somehow get the value I set via the wrapper
Console.WriteLine(fancy.level2);
Console.ReadLine();
}
}
EDIT: Fancy classes cannot be changed since they are part of an interface!
Depending on how many Fancy classes you are dealing with, you could create an adapter/facade class for each the expose a common interface. eg:
class Fancy1
{
public double level1;
public bool isEnable1;
public double level2;
public bool isEnable2;
public double level3;
}
public class FieldWrapper
{
private Action<double> _levelSetter;
private Func<double> _levelGetter;
private Action<bool> _enableSetter;
private Func<bool> _enableGetter;
public double level { get { return _levelGetter(); } set { _levelSetter(value); }}
public bool isEnabled { get { return _enableGetter(); } set { _enableSetter(value); }}
internal FieldWrapper(Func<double> levelGetter, Action<double> levelSetter, Func<bool> enableGetter, Action<bool> enableSetter)
{
_levelGetter = levelGetter;
_levelSetter = levelSetter;
_enableGetter = enableGetter;
_enableSetter = enableSetter;
}
}
abstract class FancyWrapper
{
public FieldWrapper[] Fields { get; protected set; }
}
class Fancy1Wrapper : FancyWrapper
{
private Fancy1 _fancy1;
public Fancy1Wrapper(Fancy1 fancy1)
{
_fancy1 = fancy1;
this.Fields = new[] { new FieldWrapper(() => fancy1.level1, level => _fancy1.level1 = level, () => _fancy1.isEnable1, enable => _fancy1.isEnable1 = enable),
new FieldWrapper(() => fancy1.level2, level => _fancy1.level2 = level, () => _fancy1.isEnable2, enable => _fancy1.isEnable2 = enable), };
}
}
Or you could invest 5 minutes learning data structures. Consider following example:
var levels = new Dictionary<int, bool>
{
{1, true},
{2, false}
};
if (levels[1])
{
//will run, because level 1 is true
}
if (levels[2])
{
//will not run, because level 2 is false
}
if (levels.ContainsKey(3) && levels[3])
{
//will not run, because dictionary does not contain entry for key 3
}
levels.Add(3, false);
if (levels.ContainsKey(3) && levels[3])
{
//will not run, because level 3 is false
}
levels[3] = true;
if (levels.ContainsKey(3) && levels[3])
{
//will run, because level 3 is true
}
That may seem like what you want, but it really isn't. It is extremely awkward on any number of levels. More specifically, pointers are generally rather "Un-C#-like" and having to know about these numbers defeats the point of having separate classes to begin with.
Think closely about what you want to accomplish. If you're having problems translating it into code, we're here to help. :)

Get Property of generic type object without knowing the generic type

I need to see a property of an object which is of a generic type, without knowing the specific type:
foreach(var n in Nodes)
{
if(n.GetType().GetGenericTypeDefinition() == typeof(VariableNode<>))
{
if((n as VariableNode<>).Variable == myVar) //obviously this does not work
{
toRemove.Add(n);
}
}
}
So, what would be the most elegant way to check the property "Variable" ? (variable is a reference type)
Thanks!
EDIT:
Def of Node:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using UnityEngine;
using KSPComputer.Types;
using KSPComputer.Connectors;
namespace KSPComputer.Nodes
{
[Serializable]
public abstract class Node
{
public SVector2 Position;
public int InputCount
{
get
{
return inputs.Count;
}
}
public int OutputCount
{
get
{
return outputs.Count;
}
}
public FlightProgram Program { get; private set; }
private Dictionary<string, ConnectorIn> inputs;
private Dictionary<string, ConnectorOut> outputs;
public KeyValuePair<string, ConnectorIn>[] Inputs
{
get
{
return inputs.ToArray();
}
}
public KeyValuePair<string, ConnectorOut>[] Outputs
{
get
{
return outputs.ToArray();
}
}
public Node()
{
Position = new SVector2();
inputs = new Dictionary<string, ConnectorIn>();
outputs = new Dictionary<string, ConnectorOut>();
}
internal virtual void Init(FlightProgram program)
{
Program = program;
OnCreate();
}
protected void In<T>(string name, bool allowMultipleConnections = false)
{
var connector = new ConnectorIn(typeof(T), allowMultipleConnections);
connector.Init(this);
inputs.Add(name, connector);
}
protected void Out<T>(string name, bool allowMultipleConnections = true)
{
var connector = new ConnectorOut(typeof(T), allowMultipleConnections);
connector.Init(this);
outputs.Add(name, connector);
}
protected void Out(string name, object value)
{
ConnectorOut o;
if (outputs.TryGetValue(name, out o))
{
if (o.Connected)
{
o.SendData(value);
}
}
}
protected ConnectorOut GetOuput(string name, bool connected = true)
{
ConnectorOut o;
if (outputs.TryGetValue(name, out o))
{
if (o.Connected || !connected)
{
return o;
}
}
return null;
}
protected ConnectorIn In(string name)
{
ConnectorIn o;
if (inputs.TryGetValue(name, out o))
{
return o;
}
return null;
}
public void UpdateOutputData()
{
RequestInputUpdates();
OnUpdateOutputData();
}
protected virtual void OnUpdateOutputData()
{ }
protected virtual void OnCreate()
{ }
protected void RequestInputUpdates()
{
foreach (var i in inputs.Values)
{
i.FreshData = false;
}
foreach (var i in inputs.Values)
{
if (!i.FreshData)
{
i.RequestData();
}
}
}
public IEnumerable<Connector> GetConnectedConnectors()
{
return (from c in inputs.Values where c.Connected select c as Connector).Concat(from c in outputs.Values where c.Connected select c as Connector);
}
public IEnumerable<Connector> GetConnectedConnectorsIn()
{
return (from c in inputs.Values where c.Connected select c as Connector);
}
public IEnumerable<Connector> GetConnectedConnectorsOut()
{
return (from c in outputs.Values where c.Connected select c as Connector);
}
}
}
Definition of VariableNode:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using KSPComputer;
using KSPComputer.Nodes;
using KSPComputer.Connectors;
using KSPComputer.Variables;
namespace KSPComputer.Nodes
{
[Serializable]
public class VariableNode<T> : ExecutableNode
{
internal Variable Variable { get; private set; }
internal void SetVariable(Variable variable)
{
this.Variable = variable;
}
protected override void OnCreate()
{
In<T>("Set");
Out<T>("Get");
}
protected override void OnExecute(ConnectorIn input)
{
Variable.Value = In("Set").Get<T>();
ExecuteNext();
}
protected override void OnUpdateOutputData()
{
Out("Get", Variable.Value);
}
}
}
It looks like you should be able to use reflection:
foreach(var n in Nodes)
{
if(n.GetType().GetGenericTypeDefinition() == typeof(VariableNode<>))
{
if(n.GetType().GetProperty("Variable").GetValue(n, null) == myVar)
{
toRemove.Add(n);
}
}
}
The other solution would be defining a non-generic base class for your VariableNode then you can put your non-generic property there, and finally you can easily cast your node as the base or interface and get the value of your property. Having a non generic base is quite popular practice.

foreach dictionary to check derived class

I have a base class Rules.cs. There are 2 derived classes RowRules.cs and ColumnRules.cs. I have another class Test.cs. This class has a Dictionary <int, Rules> which keeps adding the values. When I loop through the dictionary I need to know if the value is a RowRule or a ColumnRule. To better understand I have the code below.
Rules.cs
class Rules
{
private int m_timepointId = 0;
private int m_studyId = 0;
public int TimepointId
{
get { return m_timepointId; }
set { m_timepointId = value;}
}
public int StudyId
{
get { return m_studyId; }
set {m_studyId = value; }
}
}
RowRules.cs
class RowRules : Rules
{
private int m_row;
public int Row
{
get { return m_row; }
set { m_row = value; }
}
}
ColumnRules.cs
class ColumnRules: Rules
{
private int m_column;
public int Column
{
get { return m_column; }
set { m_column = value; }
}
}
In the main class I have
private Dictionary<int, Rules> m_testDictionary = new Dictionary<int, Rules>();
ColumnRules columnrules = new ColumnRules();
RowRules rowRules = new RowRules();
rowRules.Row = 1;
rowRules.StudyId = 1;
m_testDictionary.Add(1, rowRules);
columnRules.Column = 2;
columnRules.TimepointId = 2;
m_testDictionary.Add(2, columnRules);
foreach(.... in m_testDictionary)
{
//Need code here.
//if(... == RowRules)
{
}
}
Now, I need to know what value will go in the foreach loop. Also, I need to know whether that particular dictionary row is a RowRule or a ColumnRule. Hope I am clear with the question. Any help will be really appreciated.
There are a bunch of answers that are telling you to test the type using "is". That's fine, but in my opinion if you're switching off the type of an object, you're probably doing something wrong.
Typically, derived classes are used when you need additional and varied functionality from a base class. Moreover, ad-hoc polymorphism via virtual and abstract methods means that you can let the run-time figure out the type, leading to significantly cleaner code.
For example, in your case, you might want to make Rules an abstract class, with an abstract ApplyRule() method. Then, each subclass can implement the method, with the full knowledge of what it means to be a rule of that type:
public class Rules
{
private int m_timepointId = 0;
private int m_studyId = 0;
public int TimepointId
{
get { return m_timepointId; }
set { m_timepointId = value;}
}
public int StudyId
{
get { return m_studyId; }
set {m_studyId = value; }
}
// New method
public abstract void ApplyRule();
}
class RowRules : Rules
{
private int m_row;
public int Row
{
get { return m_row; }
set { m_row = value; }
}
public override void ApplyRule() { // Row specific implementation }
}
class ColumnRules : Rules
{
private int m_column;
public int Column
{
get { return m_column; }
set { m_column = value; }
}
public override void ApplyRule() { // Column specific implementation }
}
Now, your loop is just:
foreach(var kvp in m_testDictionary)
{
kvp.Value.ApplyRule();
}
This should work:
foreach(KeyValuePair<int, Rules> pair in m_testDictionary)
{
if(pair.Value is RowRule)
{
// do row rule stuff
}
if(pair.Value is ColumnRule)
{
// do row column rule stuff
}
}
Here is more information on the is keyword.
Try the following
foreach(var rule in in m_testDictionary.Values)
{
var rowRules = rule as RowRules;
if (rowRules != null) {
// It's a RowRules
continue;
}
var columnRules = rule as ColumnRules;
if (columnRules != null) {
// It's a ColumnRules
continue;
}
}
You can try this:
foreach(var key in m_testDictionary.Keys)
{
var value = m_testDictionary[key];
if(value is RowRules)
{
//test your code.....
}
}
does that code work? You have added the same key twice I believe. This is the code you wanted I believe:
foreach(int key in m_testDictionary.Keys)
{
RowRules row = m_testDictionary[key] as RowRules;
if(row !=null)
{
//code here:)
}
}

ReaderWriterLockSlim Extension Method Performance

I've been playing with collections and threading and came across the nifty extension methods people have created to ease the use of ReaderWriterLockSlim by allowing the IDisposable pattern.
However, I believe I have come to realize that something in the implementation is a performance killer. I realize that extension methods are not supposed to really impact performance, so I am left assuming that something in the implementation is the cause... the amount of Disposable structs created/collected?
Here's some test code:
using System;
using System.Collections.Generic;
using System.Threading;
using System.Diagnostics;
namespace LockPlay {
static class RWLSExtension {
struct Disposable : IDisposable {
readonly Action _action;
public Disposable(Action action) {
_action = action;
}
public void Dispose() {
_action();
}
} // end struct
public static IDisposable ReadLock(this ReaderWriterLockSlim rwls) {
rwls.EnterReadLock();
return new Disposable(rwls.ExitReadLock);
}
public static IDisposable UpgradableReadLock(this ReaderWriterLockSlim rwls) {
rwls.EnterUpgradeableReadLock();
return new Disposable(rwls.ExitUpgradeableReadLock);
}
public static IDisposable WriteLock(this ReaderWriterLockSlim rwls) {
rwls.EnterWriteLock();
return new Disposable(rwls.ExitWriteLock);
}
} // end class
class Program {
class MonitorList<T> : List<T>, IList<T> {
object _syncLock = new object();
public MonitorList(IEnumerable<T> collection) : base(collection) { }
T IList<T>.this[int index] {
get {
lock(_syncLock)
return base[index];
}
set {
lock(_syncLock)
base[index] = value;
}
}
} // end class
class RWLSList<T> : List<T>, IList<T> {
ReaderWriterLockSlim _rwls = new ReaderWriterLockSlim();
public RWLSList(IEnumerable<T> collection) : base(collection) { }
T IList<T>.this[int index] {
get {
try {
_rwls.EnterReadLock();
return base[index];
} finally {
_rwls.ExitReadLock();
}
}
set {
try {
_rwls.EnterWriteLock();
base[index] = value;
} finally {
_rwls.ExitWriteLock();
}
}
}
} // end class
class RWLSExtList<T> : List<T>, IList<T> {
ReaderWriterLockSlim _rwls = new ReaderWriterLockSlim();
public RWLSExtList(IEnumerable<T> collection) : base(collection) { }
T IList<T>.this[int index] {
get {
using(_rwls.ReadLock())
return base[index];
}
set {
using(_rwls.WriteLock())
base[index] = value;
}
}
} // end class
static void Main(string[] args) {
const int ITERATIONS = 100;
const int WORK = 10000;
const int WRITE_THREADS = 4;
const int READ_THREADS = WRITE_THREADS * 3;
// create data - first List is for comparison only... not thread safe
int[] copy = new int[WORK];
IList<int>[] l = { new List<int>(copy), new MonitorList<int>(copy), new RWLSList<int>(copy), new RWLSExtList<int>(copy) };
// test each list
Thread[] writeThreads = new Thread[WRITE_THREADS];
Thread[] readThreads = new Thread[READ_THREADS];
foreach(var list in l) {
Stopwatch sw = Stopwatch.StartNew();
for(int k=0; k < ITERATIONS; k++) {
for(int i = 0; i < writeThreads.Length; i++) {
writeThreads[i] = new Thread(p => {
IList<int> il = p as IList<int>;
int c = il.Count;
for(int j = 0; j < c; j++) {
il[j] = j;
}
});
writeThreads[i].Start(list);
}
for(int i = 0; i < readThreads.Length; i++) {
readThreads[i] = new Thread(p => {
IList<int> il = p as IList<int>;
int c = il.Count;
for(int j = 0; j < c; j++) {
int temp = il[j];
}
});
readThreads[i].Start(list);
}
for(int i = 0; i < readThreads.Length; i++)
readThreads[i].Join();
for(int i = 0; i < writeThreads.Length; i++)
writeThreads[i].Join();
};
sw.Stop();
Console.WriteLine("time: {0} class: {1}", sw.Elapsed, list.GetType());
}
Console.WriteLine("DONE");
Console.ReadLine();
}
} // end class
} // end namespace
Here's a typical result:
time: 00:00:03.0965242 class: System.Collections.Generic.List`1[System.Int32]
time: 00:00:11.9194573 class: LockPlay.Program+MonitorList`1[System.Int32]
time: 00:00:08.9510258 class: LockPlay.Program+RWLSList`1[System.Int32]
time: 00:00:16.9888435 class: LockPlay.Program+RWLSExtList`1[System.Int32]
DONE
As you can see, using the extensions actually makes the performance WORSE than just using lock (monitor).
Looks like its the price of instantiating millions of structs and the extra bit of invocations.
I would go as far as to say that the ReaderWriterLockSlim is being misused in this sample, a lock is good enough in this case and the performance edge you get with the ReaderWriterLockSlim is negligible compared to the price of explaining these concepts to junior devs.
You get a huge advantage with reader writer style locks when it takes a non-negligable amount of time to perform reads and writes. The boost will be biggest when you have a predominantly read based system.
Try inserting a Thread.Sleep(1) while the locks are acquired to see how huge a difference it makes.
See this benchmark:
Time for Test.SynchronizedList`1[System.Int32] Time Elapsed 12310 ms
Time for Test.ReaderWriterLockedList`1[System.Int32] Time Elapsed 547 ms
Time for Test.ManualReaderWriterLockedList`1[System.Int32] Time Elapsed 566 ms
In my benchmarking I do not really notice much of a difference between the two styles, I would feel comfortable using it provided it had some finalizer protection in case people forget to dispose ....
using System.Threading;
using System.Diagnostics;
using System.Collections.Generic;
using System;
using System.Linq;
namespace Test {
static class RWLSExtension {
struct Disposable : IDisposable {
readonly Action _action;
public Disposable(Action action) {
_action = action;
}
public void Dispose() {
_action();
}
}
public static IDisposable ReadLock(this ReaderWriterLockSlim rwls) {
rwls.EnterReadLock();
return new Disposable(rwls.ExitReadLock);
}
public static IDisposable UpgradableReadLock(this ReaderWriterLockSlim rwls) {
rwls.EnterUpgradeableReadLock();
return new Disposable(rwls.ExitUpgradeableReadLock);
}
public static IDisposable WriteLock(this ReaderWriterLockSlim rwls) {
rwls.EnterWriteLock();
return new Disposable(rwls.ExitWriteLock);
}
}
class SlowList<T> {
List<T> baseList = new List<T>();
public void AddRange(IEnumerable<T> items) {
baseList.AddRange(items);
}
public virtual T this[int index] {
get {
Thread.Sleep(1);
return baseList[index];
}
set {
baseList[index] = value;
Thread.Sleep(1);
}
}
}
class SynchronizedList<T> : SlowList<T> {
object sync = new object();
public override T this[int index] {
get {
lock (sync) {
return base[index];
}
}
set {
lock (sync) {
base[index] = value;
}
}
}
}
class ManualReaderWriterLockedList<T> : SlowList<T> {
ReaderWriterLockSlim slimLock = new ReaderWriterLockSlim();
public override T this[int index] {
get {
T item;
try {
slimLock.EnterReadLock();
item = base[index];
} finally {
slimLock.ExitReadLock();
}
return item;
}
set {
try {
slimLock.EnterWriteLock();
base[index] = value;
} finally {
slimLock.ExitWriteLock();
}
}
}
}
class ReaderWriterLockedList<T> : SlowList<T> {
ReaderWriterLockSlim slimLock = new ReaderWriterLockSlim();
public override T this[int index] {
get {
using (slimLock.ReadLock()) {
return base[index];
}
}
set {
using (slimLock.WriteLock()) {
base[index] = value;
}
}
}
}
class Program {
private static void Repeat(int times, int asyncThreads, Action action) {
if (asyncThreads > 0) {
var threads = new List<Thread>();
for (int i = 0; i < asyncThreads; i++) {
int iterations = times / asyncThreads;
if (i == 0) {
iterations += times % asyncThreads;
}
Thread thread = new Thread(new ThreadStart(() => Repeat(iterations, 0, action)));
thread.Start();
threads.Add(thread);
}
foreach (var thread in threads) {
thread.Join();
}
} else {
for (int i = 0; i < times; i++) {
action();
}
}
}
static void TimeAction(string description, Action func) {
var watch = new Stopwatch();
watch.Start();
func();
watch.Stop();
Console.Write(description);
Console.WriteLine(" Time Elapsed {0} ms", watch.ElapsedMilliseconds);
}
static void Main(string[] args) {
int threadCount = 40;
int iterations = 200;
int readToWriteRatio = 60;
var baseList = Enumerable.Range(0, 10000).ToList();
List<SlowList<int>> lists = new List<SlowList<int>>() {
new SynchronizedList<int>() ,
new ReaderWriterLockedList<int>(),
new ManualReaderWriterLockedList<int>()
};
foreach (var list in lists) {
list.AddRange(baseList);
}
foreach (var list in lists) {
TimeAction("Time for " + list.GetType().ToString(), () =>
{
Repeat(iterations, threadCount, () =>
{
list[100] = 99;
for (int i = 0; i < readToWriteRatio; i++) {
int ignore = list[i];
}
});
});
}
Console.WriteLine("DONE");
Console.ReadLine();
}
}
}
The code appears to use a struct to avoid object creation overhead, but doesn't take the other necessary steps to keep this lightweight. I believe it boxes the return value from ReadLock, and if so negates the entire advantage of the struct. This should fix all the issues and perform just as well as not going through the IDisposable interface.
Edit: Benchmarks demanded. These results are normalized so the manual method (call Enter/ExitReadLock and Enter/ExitWriteLock inline with the protected code) have a time value of 1.00. The original method is slow because it allocates objects on the heap that the manual method does not. I fixed this problem, and in release mode even the extension method call overhead goes away leaving it identically as fast as the manual method.
Debug Build:
Manual: 1.00
Original Extensions: 1.62
My Extensions: 1.24
Release Build:
Manual: 1.00
Original Extensions: 1.51
My Extensions: 1.00
My code:
internal static class RWLSExtension
{
public static ReadLockHelper ReadLock(this ReaderWriterLockSlim readerWriterLock)
{
return new ReadLockHelper(readerWriterLock);
}
public static UpgradeableReadLockHelper UpgradableReadLock(this ReaderWriterLockSlim readerWriterLock)
{
return new UpgradeableReadLockHelper(readerWriterLock);
}
public static WriteLockHelper WriteLock(this ReaderWriterLockSlim readerWriterLock)
{
return new WriteLockHelper(readerWriterLock);
}
public struct ReadLockHelper : IDisposable
{
private readonly ReaderWriterLockSlim readerWriterLock;
public ReadLockHelper(ReaderWriterLockSlim readerWriterLock)
{
readerWriterLock.EnterReadLock();
this.readerWriterLock = readerWriterLock;
}
public void Dispose()
{
this.readerWriterLock.ExitReadLock();
}
}
public struct UpgradeableReadLockHelper : IDisposable
{
private readonly ReaderWriterLockSlim readerWriterLock;
public UpgradeableReadLockHelper(ReaderWriterLockSlim readerWriterLock)
{
readerWriterLock.EnterUpgradeableReadLock();
this.readerWriterLock = readerWriterLock;
}
public void Dispose()
{
this.readerWriterLock.ExitUpgradeableReadLock();
}
}
public struct WriteLockHelper : IDisposable
{
private readonly ReaderWriterLockSlim readerWriterLock;
public WriteLockHelper(ReaderWriterLockSlim readerWriterLock)
{
readerWriterLock.EnterWriteLock();
this.readerWriterLock = readerWriterLock;
}
public void Dispose()
{
this.readerWriterLock.ExitWriteLock();
}
}
}
My guess (you would need to profile to verify) is that the performance drop isn't from creating the Disposable instances (they should be fairly cheap, being structs). Instead I expect it's from creating the Action delegates. You could try changing the implementation of your Disposable struct to store the instance of ReaderWriterLockSlim instead of creating an Action delegate.
Edit: #280Z28's post confirms that it's the heap allocation of Action delegates that's causing the slowdown.

Categories