Search code examples
c#event-handlingcustom-events

C# Event Handling involving publisher subscriber not working


I have a publisher class and a subscriber class. The publisher class has an event and the subscriber wants to execute one of its own methods when this event is raised.

Here is my publisher class with its event:

public delegate EventHandler<MyEventArgs> MyEventHandler(object sender, MyEventArgs args);
public class MyEventArgs : EventArgs
{
    public string Content { set; get; }
}

public class Publisher
{
    public event MyEventHandler MyCustomEvent;

    public void TriggerEvent()
    {
        if(MyCustomEvent!=null)
            MyCustomEvent(this, new MyEventArgs{ Content = "Geeee! This isn't working!" });
    }
}

And here is the subscriber:

class Subscriber
{
    static void Main(string[] args)
    {
        Publisher publisher = new Publisher();

        //hook the event to a method
        publisher.MyCustomEvent += (s, e) => delegate
        {
            PrintThis(e.Content);
        };

       //Do something to trigger the event    
        publisher.TriggerEvent();
    }
    static public void PrintThis(string content)
    {
        Console.Write(content);
    }
}

The publisher should not be aware of the subscriber. I want the subscriber to be able to execute its PrintThis function when the publisher invokes the event. But this is not working. What am I doing wrong here?


Solution

  • You haven't defined the event handler properly.

    Do it like this:

    public delegate void MyEventHandler(object sender, MyEventArgs args);
    

    Notice that the return type is void.

    And then the event handler itself should be:

        publisher.MyCustomEvent += (s, e) =>
        {
            PrintThis(e.Content);
        };
    

    Also your TriggerEvent method is safer if defined this way:

    public void TriggerEvent()
    {
        var mce = MyCustomEvent;
        if (mce!=null)
        {
            mce(this, new MyEventArgs{ Content = "Geeee! This isn't working!" });
        }
    }
    

    In a multi-threaded environment the MyCustomEvent handler could change between the null check and the invocation.