How to dispatch events in C#

淺唱寂寞╮ 提交于 2019-11-26 14:37:58

There is a pattern that is used in all library classes. It is recommended for your own classes too, especially for framework/library code. But nobody will stop you when you deviate or skip a few steps.

Here is a schematic based on the simplest event-delegate, System.Eventhandler.

// The delegate type. This one is already defined in the library, in the System namespace
// the `void (object, EventArgs)` signature is also the recommended pattern
public delegate void Eventhandler(object sender, Eventargs args);  

// your publishing class
class Foo  
{
    public event EventHandler Changed;    // the Event

    protected virtual void OnChanged()    // the Trigger method, called to raise the event
    {
        // make a copy to be more thread-safe
        EventHandler handler = Changed;   

        if (handler != null)
        {
            // invoke the subscribed event-handler(s)
            handler(this, EventArgs.Empty);  
        }
    }

    // an example of raising the event
    void SomeMethod()
    {
       if (...)        // on some condition
         OnChanged();  // raise the event
    }
}

And how to use it:

// your subscribing class
class Bar
{       
    public Bar()
    {
        Foo f = new Foo();
        f.Changed += Foo_Changed;    // Subscribe, using the short notation
    }

    // the handler must conform to the signature
    void Foo_Changed(object sender, EventArgs args)  // the Handler (reacts)
    {
        // the things Bar has to do when Foo changes
    }
}

And when you have information to pass along:

class MyEventArgs : EventArgs    // guideline: derive from EventArgs
{
    public string Info { get; set; }
}

class Foo  
{
    public event EventHandler<MyEventArgs> Changed;    // the Event
    ...
    protected virtual void OnChanged(string info)      // the Trigger
    {
        EventHandler handler = Changed;   // make a copy to be more thread-safe
        if (handler != null)
        {
           var args = new MyEventArgs(){Info = info};  // this part will vary
           handler(this, args);  
        }
    }
}

class Bar
{       
   void Foo_Changed(object sender, MyEventArgs args)  // the Handler
   {
       string s = args.Info;
       ...
   }
}

Update

Starting with C# 6 the calling code in the 'Trigger' method has become a lot easier, the null test can be shortened with the null-conditional operator ?. without making a copy while keeping thread-safety:

protected virtual void OnChanged(string info)   // the Trigger
{
    var args = new MyEventArgs{Info = info};    // this part will vary
    Changed?.Invoke(this, args);
}
Joel

Events in C# use delegates.

public static event EventHandler<EventArgs> myEvent;

static void Main()
{
   //add method to be called
   myEvent += Handler;

   //call all methods that have been added to the event
   myEvent(this, EventArgs.Empty);
}

static void Handler(object sender, EventArgs args)
{
  Console.WriteLine("Event Handled!");
}

Using the typical .NET event pattern, and assuming you don't need any special arguments in your event. Your typical event and dispatch pattern looks like this.

public class MyClassWithEvents
    {
        public event EventHandler MyEvent;

        protected void OnMyEvent(object sender, EventArgs eventArgs)
        {
            if (MyEvent != null)
            {
                MyEvent(sender, eventArgs);
            }
        }

        public void TriggerMyEvent()
        {
            OnMyEvent(sender, eventArgs);
        }
    }

Tying something into the event can be as simple as:

public class Program
{
    public static void Main(string[] args)
    {
        MyClassWithEvents obj = new MyClassWithEvents();

        obj.MyEvent += obj_myEvent;
    }

    private static void obj_myEvent(object sender, EventArgs e)
    {
        //Code called when my event is dispatched.
    }
}

Take a look at the links on this MSDN page

Look into 'delegates'.

  • Define a delegate
  • Use the delegate type as field/property (adding the 'Event' keyword)
  • You are now exposing events that users can hook into with "+= MyEventMethod;"

Hope this helps,

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!