Interlocked.Increment를 사용하여 개체의 정수 멤버를 증가 시키길 원하지만 리플렉션을 통해 해당 정수를 참조하고자합니다. 아래 코드는 작동하지 않는 예제 코드입니다.연동 됨. 반영된 값 유형의 증가
public class StatBoard
{
#region States (count of)
public int Active;
public int Contacting;
public int Polling;
public int Connected;
public int Waiting;
public int Idle;
#endregion
protected IEnumerable<FieldInfo> states;
public StatBoard()
{
Type foo = GetType();
FieldInfo[] fields = foo.GetFields(BindingFlags.Instance & BindingFlags.Public);
states = from n in fields
where n.FieldType == typeof(int)
select n;
}
public void UpdateState(string key)
{
FieldInfo statusType = states.First(
i => i.Name == key
);
System.Threading.Interlocked.Increment(ref (int)statusType.GetValue(this));
}
}
이 작업을 수행하려면 어떻게 UpdateState 메서드를 수정해야합니까?
잠금/모니터를 처음 사용하지 않는 이유는 무엇입니까? 리플렉션을 수행하는 경우 Interlocked.Increment()의 성능 이점은 보이지 않을 수도 있습니다. 게다가 다른 사람이 같은 변수를 수정하거나 (예를 들어 리플렉션 없음) 동시에 (자물쇠에 관계없이) 수정할 수 있는지 확인할 수 없습니다. –