我正在尝试使用c#中的threadPool来激活一个事件。 问题是,它向我指出事件指向NULL。
public class ClientView : IView<string>
{
event Presenter.func ViewChanged; }
event Presenter.func IView<string>.ViewChanged
{ add{}
remove{} }
public void ClientConnection()
{
while (true)
{
int recv = Client.Receive(data);
if (recv == 0) break;
userInput = Encoding.ASCII.GetString(data, 0, recv);
ViewChanged(); //here it crashes because it's null
}
Client.Close();
}
class Presenter {
private IView<string> view;
public delegate void func();
public Presenter(IView<string> view)
{
this.options = new Dictionary<string, ICommandable>();
options.Add("generate", new Option1());
this.view = view;
this.view.ViewChanged += delegate ()
{
string[] input = view.GetUserInput().Split(' ');
ThreadPool.QueueUserWorkItem(options[input[0]].execute, input);
}; }
我不明白程序崩溃的原因。我的事件ViewChanged没有指向NULL,因为我添加了代理..没有?
答案 0 :(得分:1)
如果没有订阅事件处理程序,您的应用程序将崩溃。可能您已经在附加事件处理程序之前收到了数据。
如果您使用的是C#6.0,请尝试将ViewChanged()
更改为ViewChanged?.Invoke()
,否则在调用之前应检查ViewChanged() != null
是否正确。
答案 1 :(得分:0)
自从我上次使用C#已经过了几个季节,所以这可能不是“答案”,但是......我质疑“+ =”运算符的使用以及你似乎是的事实调用“delegate()”而不是引用其地址。这段代码对我来说不合适。 。 。 (如果我有错误,请在此回复中添加评论!)