[Last Call] Learn how to a build a cloud-first strategyRegister Now

x
?
Solved

NEWBIE: Are delegates the ONLY event-handling option in C#?

Posted on 2006-05-08
11
Medium Priority
?
252 Views
Last Modified: 2010-04-16
Dear Experts,

I'm very surprised to learn that event subscribers in C# don't get an actual callback.  (I should say I'm a UI dummy in general--not just with C#.)

Are delegates the only choice for event handling in C#?  Can the subscriber ever get a chance to respond to an event directly?

Thanks,
BrianMc1958
0
Comment
Question by:BrianMc1958
  • 4
  • 3
  • 3
  • +1
11 Comments
 
LVL 48

Accepted Solution

by:
AlexFM earned 200 total points
ID: 16631410
Callback can be done using event parameters or return value.
This is axample of feedback using return value:

    delegate bool AllowPrintHandler();

    class EventSource
    {
        public event AllowPrintHandler OnAllowPrint;

        public EventSource()
        {

        }

        public void DoSomething()
        {
            if ( OnAllowPrint != null )
            {
                if ( OnAllowPrint() )
                {
                    Console.WriteLine("My subscriber allows me to print this!");
                }
                else
                {
                    Console.WriteLine("My subscriber doesn't allow me to print, but I am still printing!");
                }
            }
        }
    };

    class EventSubscriber
    {
        public EventSubscriber(bool allowToPrint)
        {
            this.allowToPrint = allowToPrint;
        }

        public void DoSomething()
        {
            EventSource source = new EventSource();
            source.OnAllowPrint += new AllowPrintHandler(source_OnAllowPrint);
            source.DoSomething();
        }

        bool  source_OnAllowPrint()
        {
               return allowToPrint;
        }

        bool allowToPrint;
    };


        static void Main(string[] args)
        {
            EventSubscriber subscriber1 = new EventSubscriber(false);
            subscriber1.DoSomething();

            EventSubscriber subscriber2 = new EventSubscriber(true);
            subscriber2.DoSomething();
        }

Result:
My subscriber doesn't allow me to print, but I am still printing!
My subscriber allows me to print this!
0
 
LVL 52

Expert Comment

by:Carl Tawn
ID: 16631418
Not quite sure what you mean. The delegate is used to tell notifier which method of the subscriber to call when a particular event happens.

What do you mean by "respond to an event directly" ?
0
 

Author Comment

by:BrianMc1958
ID: 16631603
To AlexFM:  I'll be pondering your response for a little while...

To carl_tawn:  My (quite possibly wrong) understanding of delegates so far is that the delegate has a life of it's own.  The "method" actually called is no longer a part of the subscriber at the time it is called.  It is not that notifier calls a method IN the subscriber. (For that matter, the actual notifier is the CLR). Therefore, any information the delegate needs must be pre-loaded into the delegate itself.  It can't call home to get the value of some local variable from the subscriber, for instance.  Am I interpreting all this more or less correctly?

0
VIDEO: THE CONCERTO CLOUD FOR HEALTHCARE

Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

 
LVL 52

Assisted Solution

by:Carl Tawn
Carl Tawn earned 200 total points
ID: 16631679
>>> The "method" actually called is no longer a part of the subscriber at the time it is called

I'm sure somebody will correct this if I am wrong. But as far as I am aware the original subscriber object still has to exist when the event is raised by the notifier. The delegate is essentially a function pointer, therefore the function that it points to must exist, and must be valid in order to receive the event. The method called by the event is part of an actual object and therefore all of the objects internal data and methods are available in the event handler.

Just an additional note about AlexFM's sample. If multiple objects subscribe to an event and they all return a value, the notifier will only receive the return value of the last subscriber.
0
 
LVL 48

Expert Comment

by:AlexFM
ID: 16631732
I hope this explanation can help by some way:
Delegate is pointer to function. Delegate instance is initialized with function ( like new MyDelegate(this.SomeFunction) ), and this delegate instance can be passed to any place and used to call this function later. Delegate doesn't conatin anything except address of function.

Event is actually list of delegates. When client subscribes to event, it passes delegate to it ( source.OnSomeEvent += new MyDelegate(this.OnEvent) ). Delegate is added to the event list. List of delegates in event can be empty, contain one or number of delegates.

When event is raised by source, this actually mean:
For each delegate in list
{
   invoke function pointed by delegate
}

By such way source notifies all subscribers. Feedback is done using parameters and return value.
0
 
LVL 48

Expert Comment

by:AlexFM
ID: 16631766
>> If multiple objects subscribe to an event and they all return a value, the notifier will only receive the return value of the last subscriber.

Yes, and this happens also with parameters. This means, subscriber which is notified last can override actions done by previous subscribers.
0
 
LVL 12

Assisted Solution

by:topdog770
topdog770 earned 100 total points
ID: 16631816
Alex's example demonstrates the concept really well.

By their nature, events ( or callbacks, if you prefer ) happen AFTER something has occur somewhere else.

For example, a button is clicked.  If you have subscribed to the button's 'Clicked' event, the button will notify you that a click event HAS OCCURED, meaning that it has already taken place.

Some controls provide two two stages of an event ( Validating & Validated ) as one example where validat(ING) is called when the control is currently validating and the valid(DATED) after the control has been validated.

In some cases, you can use the first stage of the event and provide your on functionality.  

Frequently though, it's been my experience that to directly respond to an event, creating my own derived control is the easist way to handle lower lvl control events. It seems that most published events occur AFTER the control has done it's own thing, which often conflicts with what I would like it to do!



0
 

Author Comment

by:BrianMc1958
ID: 16632079
OK.  I think my confusion arose in thinking that the entire METHOD was being independently instantiated as a mini-class and sent to the CLR.  That's wrong, right?  Everyone is saying that the delegate consists of nothing but the address of the method--which exists only in the subscriber.  Do I have that right now?

I'm afraid I still haven't had time to closely read AlexFM's return value example.  (I will...)  But if I could summarize the whole thing, in C# a subscriber can either say "when the event occurs, call this method that I have inside myself--which matches your defined signature" (delegate), or "just give me a return value".  If that's the case, why not always get the return value, and call your own method yourself?

(I promise to quit asking more follow-ups on this same thread after this!)

Thank you all again,
BrianMc1958
0
 
LVL 52

Expert Comment

by:Carl Tawn
ID: 16632159
>>> Do I have that right now?

Yes.

>>> If that's the case, why not always get the return value, and call your own method yourself?

I think in this case AlexFM meant returning a value back to the notifier via either the return value from the subscribers event handler, or via the parameters passed to the subscriber with the event, rather than you simply calling a method on the notifier and getting a return value. The difference is that, whereas a return value from a method call is immediate, an event may not happen immediatley. By subscribing to the event you are simply saying "when this event happens, whenever that may be, I want to know about it".

For an example of returning a value through the event arguments, consider the Closing event of a WinForm. You can suscribe to the closing event and if for some reason you want to cancel it, you can set the Cancel property of the eventargs and prevent the form from closing.
0
 
LVL 48

Expert Comment

by:AlexFM
ID: 16632731
>> when the event occurs, call this method that I have inside myself--which matches your defined signature" (delegate).

This is exact definition of event subscription.
0
 

Author Comment

by:BrianMc1958
ID: 16632856
I think I've taken up enough of all your time for today.  This helps a lot.  I'm a lot more clear on delegates now.  I'm still struggling with the feedback, but I'll need to look at that more closely later.

Once again, thank you all for taking the time to help lessen my confusion!

--BrianMc1958
0

Featured Post

Vote for the Most Valuable Expert

It’s time to recognize experts that go above and beyond with helpful solutions and engagement on site. Choose from the top experts in the Hall of Fame or on the right rail of your favorite topic page. Look for the blue “Nominate” button on their profile to vote.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

It was really hard time for me to get the understanding of Delegates in C#. I went through many websites and articles but I found them very clumsy. After going through those sites, I noted down the points in a easy way so here I am sharing that unde…
The article shows the basic steps of integrating an HTML theme template into an ASP.NET MVC project
Is your data getting by on basic protection measures? In today’s climate of debilitating malware and ransomware—like WannaCry—that may not be enough. You need to establish more than basics, like a recovery plan that protects both data and endpoints.…
This lesson discusses how to use a Mainform + Subforms in Microsoft Access to find and enter data for payments on orders. The sample data comes from a custom shop that builds and sells movable storage structures that are delivered to your property. …
Suggested Courses
Course of the Month18 days, left to enroll

830 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question