【问题标题】:Interlocked.Increment of Reflected Value TypeInterlocked.Increment 反射值类型
【发布时间】:2010-07-17 01:35:59
【问题描述】:

我想使用 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() 的性能优势可能无论如何都看不到。此外,您无法确定其他人正在同时修改同一个变量(使用或不使用反射)(无论您如何锁定)。

标签: c# .net multithreading reflection synchronization


【解决方案1】:

这不能按设计工作。 int 是一种值类型。 GetValue() 方法返回 int 的副本。您将增加该副本,而不是原始副本。反射无法获取对值类型值的引用。

【讨论】:

  • 他可以在DynamicMethod 中使用Reflection.Emit 来访问字段类型。不过,这将是复杂而缓慢的。
猜你喜欢
  • 1970-01-01
  • 2015-09-26
  • 2020-11-23
  • 2010-09-17
  • 1970-01-01
  • 1970-01-01
  • 2018-09-13
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多