aviadm71
aviadm71

Reputation: 85

Error - event points to NULL c#

I'm trying to raisn an event using threadPool in c#. Problem is, that it points out to me that the Event points to 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);
        }; }

I do not understand why the program crashes. my event ViewChanged does not point to NULL because I added the delegates to it.. no?

Upvotes: 0

Views: 104

Answers (2)

Mike Robinson
Mike Robinson

Reputation: 8995

It's been a few seasons since I last used C#, so this might not be an "answer," but ... I question the use of the "+=" operator and the fact that you seem to be calling "delegate()" instead of referencing its address. That piece of code just doesn't look right to me . . . (And if I am in error, please add a comment to this reply!)

Upvotes: 0

Peter Keuter
Peter Keuter

Reputation: 788

Your application will crash if no event handler has subscribed. Probably you have received data before before your event handler has been attached.

Try changing ViewChanged() to ViewChanged?.Invoke() if you are using C# 6.0, else you should check if ViewChanged() != null before calling it.

Upvotes: 1

Related Questions