代码之家  ›  专栏  ›  技术社区  ›  Joel B

为什么捕获的变量不包含对对象实例的引用

  •  1
  • Joel B  · 技术社区  · 14 年前

    正如下面的代码所示,我正在foreach循环中创建一个线程,稍后再运行它们,但是当我运行该线程时,会得到“object reference not set to an instance of an object”错误。我怀疑这是一个封闭的问题,但似乎我正在做我应该做的一切来避免在这里创建一个本地的价值拷贝。如何更正此代码以完成线程的创建,然后在以后的时间,允许调用方法(线程启动)?

    foreach (ObjWithDelegateToCreateTrdFrom item in queryResult)
    {
        // Capture object state    
        ObjWithDelegateToCreateTrdFrom capturedValue = item;
    
        // Create thread from object
        Thread thread = new Thread(() =>
        {
            capturedValue.Method.Invoke(capturedValue.paramsArray)
        });
    
        // Add thread to temp thread list
        trdList.Add(thread);
    }
    
    2 回复  |  直到 14 年前
        1
  •  2
  •   Grozz    14 年前

    检查以下值:

    1. 捕获值
    2. CapturedValue.方法
    3. CapturedValue.Paramsarray参数

    在lambda主体中,即线程执行时。

    即使在创建线程时它们不是空的,也可以在初始化线程对象的时间和运行时决定执行线程对象的时间之间将它们设置为空。

        2
  •  1
  •   Steven    14 年前

    试试这个:

    foreach (ObjWithDelegateToCreateTrdFrom item in queryResult)
    {
        if (item == null)
        {
            throw new InvalidOperationException("Item is null");
        }
    
        if (item.Method == null)
        {
            throw new InvalidOperationException("Item.Method is null");
        }
    
        if (item.paramsArray == null)
        {
            throw new InvalidOperationException("Item.paramsArray is null");
        }
    
        // Create thread from object
        Thread thread = new Thread(() =>
        {
            capturedValue.Method.Invoke(capturedValue.paramsArray)
        });
    
        // Add thread to temp thread list
        trdList.Add(thread);
    }
    

    当这不能解决您的问题时,请给我们一个包含更多信息的堆栈跟踪。