Still having trouble understanding ASP.NET events. What's the point?

I may be slow, but I just donโ€™t understand why you ever used an event that was not obtained from the actual action (for example, a click). Why go through rigamarole to create delegates and events when you can just call a method? It seems that when you create an event, all you do is the way the caller can go through a complex process to invoke a simple method. And the caller must raise this event himself! I do not understand.

Or maybe I just don't understand the concept. I need events like OnClick and interactions with controls, but what about classes? I tried to implement events for my class, say, when the source of an element changed, but quickly realized that it made no sense, because I could just call the method whenever I wanted to perform a certain action instead of creating an event, creating an event and writing an event handler. In addition, I can reuse my method, while I cannot reuse an event handler.

Someone told me directly. I feel like I'm just mistaken here, and I want to be corrected. The last question I asked did not actually get any useful answer.

Thank.

+3
event-handling events
Aug 26 '09 at 20:45
source share
6 answers

I always like the metaphor of Radio Station.

When a radio station wants to transmit something, it just sends it. He does not need to know if anyone is really listening. Your radio can register with the radio station (by tuning using the dial), and all the radio stations (events in our small metaphor) receive the radio, which translates them into sound.

Without this registration mechanism (or event). The radio station should contact all the radio stations one at a time and ask if it wants to broadcast if your radio says yes, and then sends a signal to it directly.

Your code may follow a very similar paradigm, where one class performs an action, but this class may not know or do not want to know who will take care of it or act in this case. Thus, it provides an opportunity for any object to register or unregister to notify that an action has been performed.

+9
Aug 26 '09 at 21:02
source share

Events in general can be a good way to separate the listener / observer from the caller / raiser.

Consider the button. When someone clicks a button, the click event fires. Does the listener listen to the button, what does the button look like, or something like that? Most probably not. He only cares that the click action has occurred, and now it goes and does something.

The same can be applied to everything that is necessary for the same isolation / isolation. It does not have to be a managed UI, it may just be the logical separation that should take place.

+4
Aug 26 '09 at 20:49
source share

Using events has the advantage of splitting a class (es) that handle events from classes that raise them (a la observer pattern ). While this is useful for the Model View Controller (a button that triggers click events orthogonal to the class that processes them), it is also useful to anyone (at run time or not) to save a class that processes events that are separate from the class that raises them ( allows you to change or replace them).

Basically, the whole point is to keep classes that handle events separate from classes that raise them. An unnecessary connection is bad because it greatly simplifies the maintenance of the code (since changing one place in the code will require changes in any code fragments associated with it).

Edit: Most of the event handling that you will do in Asp.Net is likely to handle events from the classes that are provided to you. Since these classes use event handling, this makes it easier for you to interact with them. Often this event will also allow you to interact with the object that raised the event. For example, database controls usually raise an event just before connecting to a database that you can access to use runtime information to change the arguments passed to the stored procedure while talking to your database, for example. if the query string contains a page number parameter, and the stored procedure has a page number argument.

+2
Aug 26 '09 at 20:51
source share

Events can be used as messages to notify that something has happened, and the consumer can respond to them accordingly, so the different components are loosely coupled. There are many things you can use for events, one example is checking what is happening on the system; The audit component can use various events and log them when they are triggered.

+1
Aug 26 '09 at 20:56
source share

What seems missing to you is two:

  • Cases in the software can take an arbitrary amount of time, not only because of waiting for user input (async i / o, database queries, etc.). If you run the async i / o request, you want to subscribe to an event notifying you when the reading is done so that you can do something with the data. This idea is generalized to the .NET BackgroundWorker class, which allows you to perform heavy tasks in the background (another thread) and receive notifications in the calling thread when this is done.

  • In the software, events occur that are used by several clients, not only for one. For example, if you have a plugin architecture where your main code offers to intercept the plugin code, you can either do something like

     foreach (Plugin p in getAvaliablePlugins()) { p.hook1(); } 

    in every connection throughout your code, which reduces flexibility (p cannot decide what to do, and must provide the hook1 method publicly), or you can just

     raiseEvent(hook1,this) 

    where all registered plugins can execute their code because they receive an event, allowing them to do their job as they see fit.

+1
Aug 26 '09 at 21:17
source share

I think you are misleading ASP.NET (incorrect) use of events with simple event handling.

We will start with simple event handling. Events are another way to perform "Open [for expansion] / Closed [for modification]". When your class provides an event, it allows external classes (perhaps not yet thought-out classes, much less built ones) to have the code executed by your class. This is a fairly powerful extension mechanism, and it does not require your class to be modified in any way.

As an example, consider a web server that knows how to accept a request but does not know how to process the file (I will use bidirectional events here, where the handler can pass data back to the event source. Some say itโ€™s not kosher, but this is the first example that came to mind):

 class WebServer { public event EventHandler<RequestReceivedEventArgs> RequestReceived; void ReceiveRequest() { // lots of uninteresting network code here var e = new RequestReceivedEventArgs(); e.Request = ReadRequest(); OnRequestReceived(e); WriteResponse(e.Response); } void OnRequestReceived(RequestReceivedEventArgs e) { var h = RequestReceived; if (h != null) h(e); } } 

Without changing the source code of this class โ€” perhaps in a third-party library โ€” I can add a class that knows how to read a file from disk:

 class FileRequestProcessor { void WebServer_RequestReceived(object sender, EventArgs e) { e.Response = File.ReadAllText(e.Request); } } 

Or maybe the ASP.NET compiler:

 class AspNetRequestProcessor { void WebServer_RequestReceived(object sender, EventArgs e) { var p = Compile(e.Request); e.Response = p.Render(); } } 

Or maybe I'm just curious to know that the event happened without affecting it at all. Let's say for registration:

 class LogRequestProcessor { void WebServer_RequestReceived(object sender, EventArgs e) { File.WriteAllText("log.txt", e.Request); } } 

All of these classes basically โ€œinjectโ€ code in the middle of WebServer.OnRequestReceived .

Now, for the ugly part. ASP.NET has this annoying little habit of writing event handlers to handle your own events. So, the class inherited from ( System.Web.UI.Page ) has an event called Load :

  abstract class Page { public event EventHandler Load; virtual void OnLoad(EventArgs e) { var h = this.Load; if (h != null) h(e); } } 

and you want to run the code when the page loads. Following the Open / Closed principle, we can either inherit or override:

  class MyPage : Page { override void OnLoad(EventArgs e) { base.OnLoad(e); Response.Write("Hello World!"); } } 

or use eventing:

  class MyPage : Page { MyPage() { this.Load += Page_Load; } void Page_Load(EventArgs e) { Response.Write("Hello World!"); } } 

For some reason, Visual Studio and ASP.NET prefer an event-based approach. I suppose you can have several handlers for the Load event, and they will all fire automatically, but I never see anyone doing this. Personally, I prefer a redefinition approach - I think it is a little clearer and you will never have the question "why did I subscribe to my own events?".

+1
Aug 26 '09 at 21:18
source share



All Articles