C# 为什么捕获的变量不包含对对象实例的引用
正如下面的代码所示,我正在foreach循环中创建一个线程,并在以后运行它们,但是当我运行该线程时,会出现“object reference not set to a instance of a object”错误。我怀疑这是一个闭包问题,但似乎我正在做我应该做的一切,通过创建值的本地副本来避免这种情况。如何更正此代码以完成线程的创建,然后在以后允许调用方法(线程启动) 试试这个:C# 为什么捕获的变量不包含对对象实例的引用,c#,delegates,foreach,closures,invoke,C#,Delegates,Foreach,Closures,Invoke,正如下面的代码所示,我正在foreach循环中创建一个线程,并在以后运行它们,但是当我运行该线程时,会出现“object reference not set to a instance of a object”错误。我怀疑这是一个闭包问题,但似乎我正在做我应该做的一切,通过创建值的本地副本来避免这种情况。如何更正此代码以完成线程的创建,然后在以后允许调用方法(线程启动) 试试这个: foreach (ObjWithDelegateToCreateTrdFrom item in queryResu
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);
}
如果这不能解决您的问题,请向我们提供包含更多信息的堆栈跟踪。检查以下值:
即使它们在创建线程时不为null,也可以在初始化线程对象和运行时决定执行它之间设置为null。异常的堆栈跟踪是什么?你确定是
capturedValue
引用为空吗?我觉得你的代码很好。无论出于何种原因,capturedValue.Method
是否可能为空?(或者稍后设置为null?)查看下面我的解决方案,在我看来更准确。@Stepen-感谢代码示例!我正在lambda体内实施你的解决方案,你说得对。最好在lambda主体内执行此检查。你所说的可能发生的事情正是我的问题&我完全没有意识到这一点。
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);
}