Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to dispatch events in C#

Tags:

I wish to create own events and dispatch them. I never done this before in C#, only in Flex.. I guess there must be a lot of differencies.

Can anyone provide me a good example?

like image 365
Janov Byrnisson Avatar asked Mar 15 '10 15:03

Janov Byrnisson


People also ask

What are Dispatch events?

The dispatchEvent() method of the EventTarget sends an Event to the object, (synchronously) invoking the affected EventListener s in the appropriate order. The normal event processing rules (including the capturing and optional bubbling phase) also apply to events dispatched manually with dispatchEvent() .

How do I invoke an event in C#?

Events in C# are simple things on the face of it. You create an event signature using a delegate type and mark it with the event keyword. External code can register to receive events. When specific things occur within your class, you can easily trigger the event, notifying all external listeners.

How do you raise an event?

Typically, to raise an event, you add a method that is marked as protected and virtual (in C#) or Protected and Overridable (in Visual Basic). Name this method On EventName; for example, OnDataReceived .

What is EventArgs C#?

The EventArgs class is the base class for all the event data classes. . NET includes many built-in event data classes such as SerialDataReceivedEventArgs. It follows a naming pattern of ending all event data classes with EventArgs. You can create your custom class for event data by deriving EventArgs class.


2 Answers

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);
}
like image 97
Henk Holterman Avatar answered Sep 24 '22 07:09

Henk Holterman


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!");
}
like image 28
Joel Avatar answered Sep 22 '22 07:09

Joel