Events / delegates in Java or C #

I tried to find out about events / delegates, but I am confused about the relationship between them. I know that delegates allow you to call different functions without requiring you to know which function is being called. (for example: a graphic display function must accept inputs that are various functions that need to be graphitized).

But I do not see how delegates are used in Events.

Can someone build a simple example (in pseudocode or C # or Java) that illustrates how delegates work with events?

Thanks!

+6
java c # event-handling delegates
source share
6 answers

(All this from the point of view of C #.)

I have an article on the differences between events and delegates . This describes in more detail everything below.

Basically, I like to think that an event is like a property - it's a couple of methods, that's all. Instead of get / set, the event has add / remove, which means "add an event handler" and "remove this event handler." At the heart of everything is all events.

C # also has field-like events, which are shortcuts:

public event EventHandler Foo; 

declares both a field and an event with an almost trivial add / remove implementation. In a class related to Foo , refers to a field. Outside the class, referring to Foo , refers to the event.

The main idea is that the event allows another code to subscribe and refuse it by passing a delegate (event handler). Typically, a subscription is implemented by creating a new multicast delegate containing the previous list of event handlers and a new one. Therefore, if you store event handlers in a field called myEventHandlers , the subscription implementation may be:

 myEventHandlers += value; 

Similarly, unsubscribing usually involves creating a new multicast delegate without the specified handler:

 myEventHandlers -= value; 

Then, when you want to raise / fire an event, you simply call this multicast delegate - usually with an invalidation check to throw an exception if no one has signed up:

 EventHandler handler = myEventHandlers; if (handler != null) { // You could pass in a different "sender" and "args" of course handler(this, EventArgs.Empty); } 

Using events, subscribers do not know about each other and cannot raise the event themselves (usually). In other words, this is an example of encapsulation, which has received status both in the language and on the platform.

+8
source share

You will need to indicate which language you need. As far as I know, Java has no concept of delegates (although I could be completely wrong); he tends to follow an observer pattern for handling events.

C #, however, does. event in C # has the same relation to a delegate as a property, to its support field. The delegate itself is that it stores a pointer to a function that processes the event (or rather, a list of pointers attached to the event, I freely use the term "pointer" here).

If I declare this in C #:

 public event EventHandler MyEvent; 

And fire the event like this:

 MyEvent(this, EventArgs.Empty); 

This is really just a shorthand for implementing the full event:

 private EventHandler myEventHandler; public event EventHandler MyEvent { add { myEventHandler += value; } remove { myEventHandler -= value; } } 

And calling him ...

 myEventHandler(this, EventArgs.Empty); 

All this means that the actual event provides two operations: add and remove , which are used by the consumer code to attach their event handlers to the event. In the standard (abbreviated) notation, the compiler creates a private instance of the delegate class and uses it as I described above. When you β€œtrigger” an event, the compiler actually replaces the event name for the name of the private support delegate that it creates. This is why you cannot call event from a subclass - if the event is created in an abbreviated form, then the support element is private .

+2
source share

The difference is simple.

delegate is a class with two fields - an object and MethodInfo.

event is a private field of type delegate and two public methods add and remove .

Usually used under the hood of the MulticastDelegate event - this is a class inherited from delegate and containing a list of delegates. This allows the event to have multiple subscribers.

+2
source share

You can see: http://msdn.microsoft.com/en-us/library/17sde2xt.aspx

The example continues here: http://msdn.microsoft.com/en-us/library/xwbwks95.aspx

Basically, as already mentioned, events are only special cases of delegates, but with changes in .NET 3.5 you can record events without using delegates, although delegates are still being recorded under the hood.

If you look at this article, they show how to use lambda expressions and anonymous functions for events: http://msdn.microsoft.com/en-us/library/ms366768.aspx

+1
source share

.Net events are just delegates under the hood: they provide some syntactic sugar in the compiler.

You can set the / reset delegate, but you can add or remove an event handler. The rationale is that you don't care who else signed up for the event, while simple delegates are more used in a callback scenario.

But at the end of all things they are very similar.

Some resources:

C # events against delegates

Delegates and Events - Short Q & A

0
source share

I am new to the java world, but I have to admit that I am very enthusiastic, but I still miss some C # materials, so create this template that gave me good results, do Java experts see some drawback in using this template? It only supports java 8:

 @FunctionalInterface public interface IEvent<TEventArgs extends Object> { void invoke(TEventArgs eventArgs); } public class EventHandler<TEventArgs> { private ArrayList<IEvent<TEventArgs>> eventDelegateArray = new ArrayList<>(); public void subscribe(IEvent<TEventArgs> methodReference) { eventDelegateArray.add(methodReference); } public void unSubscribe(IEvent<TEventArgs> methodReference) { eventDelegateArray.remove(methodReference); } public void invoke(TEventArgs eventArgs) { if (eventDelegateArray.size()>0) eventDelegateArray.forEach(p -> p.invoke(eventArgs)); } } public class DummyEventProducer { // The event public EventHandler<String> myEvent = new EventHandler<>(); public void onMyEvent(String A) { myEvent.invoke(A); } } public class DummySubscriber { // The method will be subscribed to the event public void methodCallWhenEventGetTriggered(String eventArgs) { System.out.println("event fired with eventargs: " + eventArgs); } } public class Main { public static void main(String[] args) { // A dummy producer DummyEventProducer producer = new DummyEventProducer(); // A dummy subscribers DummySubscriber testingInstanceA = new DummySubscriber(); DummySubscriber testingInstanceB = new DummySubscriber(); DummySubscriber testingInstanceC = new DummySubscriber(); // We create decoupled event links because we want to un-subscribe later IEvent<String> EventSink1 = testingInstanceA::methodCallWhenEventGetTriggered; IEvent<String> EventSink2 = testingInstanceB::methodCallWhenEventGetTriggered; IEvent<String> EventSink3 = testingInstanceC::methodCallWhenEventGetTriggered; // subscribe to the event on dummy producer producer.myEvent.subscribe(EventSink1); producer.myEvent.subscribe(EventSink2); producer.myEvent.subscribe(EventSink3); // fire the event on producer producer.onMyEvent("Hola MUNDO with decoupled subscriptions!"); // unsubscribe to the event on dummy producer producer.myEvent.unSubscribe(EventSink1); producer.myEvent.unSubscribe(EventSink2); producer.myEvent.unSubscribe(EventSink3); // fire the event on producer again producer.onMyEvent("Hola MUNDO! with no events subscriptions :("); // IF YOU DON CARE ABOUT UNSUBSCRIBE YOU CAN LINK EVENTS DIRECTLY TO THE SUBSCRIBER producer.myEvent.subscribe(testingInstanceA::methodCallWhenEventGetTriggered); producer.myEvent.subscribe(testingInstanceB::methodCallWhenEventGetTriggered); producer.myEvent.subscribe(testingInstanceC::methodCallWhenEventGetTriggered); // fire the event on producer again producer.onMyEvent("Hola MUNDO! with strong link subscriptions (cannot be un-subscribed"); } } 

Feel free to ask, corrections, suggestions =) Best regards!

0
source share

All Articles