我收到此错误,无法理解此错误。 我使用win form和.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
}
}
答案 0 :(得分:0)
看起来它对我很有用。
您的计划的背景是什么?
我写了一个包含代码的简单空shell,但程序将在线程开始之前结束。
我必须添加一个Console.ReadKey()方法。
以下是我使用的完整代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
namespace DelegateToInstance {
class Program {
static void Main(string[] args) {
var obj = new Caller();
obj.button_click();
Console.ReadKey();
}
}
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
}
}
}
我讨厌选民,所以我给了你一个upvote。