An event is a wrapper for a delegate, just like a property is a wrapper for a field. A property has accessors, get and set. So does an event, they are named add and remove. Unlike a property, using the accessors isn't actually required. The add accessor is used when you assign an event handler with the += operator. The default implementation is to call Delegate.Combine() on the wrapper delegate instance. Remove (-=) removes the handler, default is Delegate.Remove(). All these things work just as well if you simple declare the delegate instance instead of using the event keyword. Just as they work well when you declare a field public instead of using a property. In the following code, you can remove the "event" keyword and it works the same: class Program { static event EventHandler MyEvent; static void Main(string[] args) { MyEvent += Target; MyEvent(null, EventArgs.Empty); MyEvent -= Target; } static void Target(object sender, EventArgs e) { Console.WriteLine("called"); } } The key point is that the accessors of an event allow a private delegate instance, preventing a client program from messing with it. Used extensively in Windows Forms for example. And the exact same strategy provided by a property. You'd make it look like this: public event EventHandler MyEvent { add { privEvent += value; } remove { privEvent -= value; } } private EventHandler privEvent; This prevents code from removing event handlers that were registered by other code. The delegate instance is private, the only way to remove a handler is to produce the right "value". Which only the code that registered the event handler can do. Okay, what's a delegate. Yes, it is a function pointer, a list of function pointers to be precise. You add a pointer to the list with Delegate.Combine(), remove one with Delegate.Remove(). += and -= in C#. But it also stores the object that is the target of the function pointer, it stores the "this" reference. That's very well hidden in C#, you never explicitly assign the reference when you register an event handler. The compiler does it for you. If the event handler is a static method then that object reference is null. Delegate.Invoke() calls the delegate targets. It enumerates the list, calling each target method (event handler) in turn. The C# sugar hides the Invoke call. The rest of your question are harder to answer. Not sure what you call a "global event". Just like any .NET class member, something is "global" when it is static and public. An example of such an event would be the events of the SystemEvents class. "Reaching the application" is not special. The application made sure that it is "reachable" by registering an event handler. Events cannot cross process boundaries by themselves, you would need one of the process interop mechanisms to bridge the wall. .NET Remoting or WCF are popular choices.
Hans Passant.- Marked As Answer byChuMak Thursday, September 24, 2009 2:03 AM
-
|