【发布时间】:2015-06-04 11:37:42
【问题描述】:
我收到此错误,无法理解此错误。 我使用 win 表格和 .net 3.5。 问题是,这可以编译和间歇性的。今天刚刚展示,所以我猜这种情况非常罕见(可能在 5000 次运行后出现)。我想知道是什么导致了这个错误,以及任何可能的解决方法。 这是我如何实现代码的示例。
我的应用是多线程的,这个方法是单例的。
Exception type: System.ArgumentException
Exception message: Delegate to an instance method cannot have null 'this'.
Exception stack trace:
at System.MulticastDelegate.ThrowNullThisInDelegateToInstance()
at System.MulticastDelegate.CtorClosed(Object target, IntPtr methodPtr)
class Caller
{
private ClassA theA;
public Caller()
{
theA = new ClassA();
}
public void button_click()
{
theA.Execute(false);
}
public void button2_click()
{
theA.Execute( true );
}
}
interface IClassA
{
void ActionMinus();
}
class ClassA
{
public int VariableA = 0;
public void Execute( bool wait )
{
ClassB instanceB = new ClassB( this );
Thread thread = new Thread( instanceB.Action ) // error in here
{
Name = "Executor",
Priority = ThreadPriority.Highest
};
thread.Start();
if( wait )
thread.Join();
}
public void ActionMinus()
{
//someAction1
VariableA -= 2;
//someAction2
}
}
class ClassB
{
private readonly ClassA instanceA;
public ClassB( ClassA instance )
{
instanceA = instance;
}
public void Action()
{
//some other action3
instanceA.VariableA += 5;
//some other action4
instanceA.ActionMinus();
//some other action5
}
}
【问题讨论】:
-
请提供重现问题的a good, minimal, complete code example(即使是间歇性的)。到目前为止,您的帖子暗示
instanceB在创建线程委托时是null,但这里没有什么可以做到这一点。缺少完整的代码示例,很难猜出实际问题是什么。 -
首先你确实有很多编译错误,比如在
ActionMinus之前缺少返回类型@ClassB之前缺少类关键字等等......解决它,你会得到很好的工作代码. -
编辑代码@PeterDuniho,我相信instanceB不为空。