Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • World
  • Users
  • Groups
Skins
  • Light
  • Cerulean
  • Cosmo
  • Flatly
  • Journal
  • Litera
  • Lumen
  • Lux
  • Materia
  • Minty
  • Morph
  • Pulse
  • Sandstone
  • Simplex
  • Sketchy
  • Spacelab
  • United
  • Yeti
  • Zephyr
  • Dark
  • Cyborg
  • Darkly
  • Quartz
  • Slate
  • Solar
  • Superhero
  • Vapor

  • Default (No Skin)
  • No Skin
Collapse
Code Project
  1. Home
  2. General Programming
  3. C#
  4. What is the correct code to invoke subscribers for an event?

What is the correct code to invoke subscribers for an event?

Scheduled Pinned Locked Moved C#
questioncsharphelp
16 Posts 5 Posters 2 Views 1 Watching
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • L Lost User

    Thank you for this. I just edited the question a Little bit :)

    B Offline
    B Offline
    BillWoodruff
    wrote on last edited by
    #4

    I'm glad that's helpful; perhaps it's a bias of mine that I think copying a pointer is "cheap" ?

    «There is a spectrum, from "clearly desirable behaviour," to "possibly dodgy behavior that still makes some sense," to "clearly undesirable behavior." We try to make the latter into warnings or, better, errors. But stuff that is in the middle category you don’t want to restrict unless there is a clear way to work around it.» Eric Lippert, May 14, 2008

    1 Reply Last reply
    0
    • L Lost User

      Let's assume we have something like this:

      public class Person : INotifyPropertyChanged
      {
      public event PropertyChangedEventHandler PropertyChanged;
      private void NotifyPropertyChanged([CallerMemberName]string propertyName = null)
      {
      // Is it really needed, to make a copy? *1)
      var handler = PropertyChanged;
      if (handler != null)
      {
      handler(this, new PropertyChangedEventArgs(propertyName));
      }
      }
      // ....
      }

      *1) Copy of the subscribers really needed? A lot of time in forums like CP I read we _need_ to make a copy of the subscribers before invoke the handlers. Argumentation: This because theoretically the subscribers can unsubscribe in between... My doubts, respectively I see only arguments why not to copy: a.) In a some lot (in most?) of MSDN examples, no copy will be made. So, when MSDN does not do it why should I do it? b.) In case someone unsubscribes he is not longer interested in the event. Why should I notify him then longer? c.) My opinion is, that it can be dangerous to inform a subscriber while he unsubscribed and therefore does not expect notifications any longer. [Edit] Thank you BillWoodruff :) Ok, a problem I see now in case I do not make a copy: In bewteen (if PropertyChanged != null) and invoking PropertyChanged(...) it is possible that one does unsubscribe. Probably this Point is solved in c#6 by using (PropertyChanged?.Invoke(...) But still "c.)" above is critical I think...(?) and the subscriber has to be aware that even after unsubscribing he can get notifications. Comments / corrections / notes will be very appreciated. Thank you in advance.

      P Offline
      P Offline
      Pete OHanlon
      wrote on last edited by
      #5

      Imagine your system has an event with one subscriber. This subscriber is on a background thread. Now, consider the case where the very last action before context switching over to the thread your subscriber is on is to check to see if you have any subscriptions. That's fine as the null check will tell you that you have a subscriber. Okay, you're now processing on this other thread and the first thing it does is to remove the event subscription. You now have nothing hooked up to the event but when you context switch back, it's going to continue as though there are subscriptions. That's why you take the copy.

      This space for rent

      L B 2 Replies Last reply
      0
      • P Pete OHanlon

        Imagine your system has an event with one subscriber. This subscriber is on a background thread. Now, consider the case where the very last action before context switching over to the thread your subscriber is on is to check to see if you have any subscriptions. That's fine as the null check will tell you that you have a subscriber. Okay, you're now processing on this other thread and the first thing it does is to remove the event subscription. You now have nothing hooked up to the event but when you context switch back, it's going to continue as though there are subscriptions. That's why you take the copy.

        This space for rent

        L Offline
        L Offline
        Lost User
        wrote on last edited by
        #6

        Thank you for your Feedback. Yes I see this Point meanwhile. On the other Hand when the subscriber unsubscribes he still has to be aware to get notified and this fact (I hope I'm right on this, that it is a fact) I never found in a discussion.

        Time Publisher Subscriber


        1 Take a copy -
        2 - Unsubscribe
        3 Invoke "Check for race condition needed before proceeding"

        P 1 Reply Last reply
        0
        • B BillWoodruff

          I think you may find Jon Skeet's comments on this relevant: [^], and his information on using an extension method, and the null-conditional operator in C#6 ... interesting. I don't pretend to understand the thread-safety and/or multiple-subscriber issues involved: for that we need Richard Deeming or Richard MacCutchan to step-up :)

          «There is a spectrum, from "clearly desirable behaviour," to "possibly dodgy behavior that still makes some sense," to "clearly undesirable behavior." We try to make the latter into warnings or, better, errors. But stuff that is in the middle category you don’t want to restrict unless there is a clear way to work around it.» Eric Lippert, May 14, 2008

          L Offline
          L Offline
          Lost User
          wrote on last edited by
          #7

          BillWoodruff wrote:

          we need Richard Deeming or Richard MacCutchan to step-up

          That's very kind but misguided I'm afraid. I could possibly give an answer, but I would need to do quite a bit of research and testing first.

          B 1 Reply Last reply
          0
          • L Lost User

            BillWoodruff wrote:

            we need Richard Deeming or Richard MacCutchan to step-up

            That's very kind but misguided I'm afraid. I could possibly give an answer, but I would need to do quite a bit of research and testing first.

            B Offline
            B Offline
            BillWoodruff
            wrote on last edited by
            #8

            I know it is your modesty that makes you suggest I may be kindly misguided to consider you (and brother Deeming) as guides non-pareil in this esoteric area, and I appreciate that quality as much as I do the depth of your technical knowledge :)

            Richard MacCutchan wrote:

            I could possibly give an answer

            Duchess to Alice (Alice’s Adventures in Wonderland, Chapter 9)

            That’s nothing to what I could say if I chose.

            «There is a spectrum, from "clearly desirable behaviour," to "possibly dodgy behavior that still makes some sense," to "clearly undesirable behavior." We try to make the latter into warnings or, better, errors. But stuff that is in the middle category you don’t want to restrict unless there is a clear way to work around it.» Eric Lippert, May 14, 2008

            L 1 Reply Last reply
            0
            • B BillWoodruff

              I know it is your modesty that makes you suggest I may be kindly misguided to consider you (and brother Deeming) as guides non-pareil in this esoteric area, and I appreciate that quality as much as I do the depth of your technical knowledge :)

              Richard MacCutchan wrote:

              I could possibly give an answer

              Duchess to Alice (Alice’s Adventures in Wonderland, Chapter 9)

              That’s nothing to what I could say if I chose.

              «There is a spectrum, from "clearly desirable behaviour," to "possibly dodgy behavior that still makes some sense," to "clearly undesirable behavior." We try to make the latter into warnings or, better, errors. But stuff that is in the middle category you don’t want to restrict unless there is a clear way to work around it.» Eric Lippert, May 14, 2008

              L Offline
              L Offline
              Lost User
              wrote on last edited by
              #9

              BillWoodruff wrote:

              know it is your modesty

              :laugh: But thank you anyway. And, to be honest I could not have produced as good an explanation as Pete's below.

              1 Reply Last reply
              0
              • L Lost User

                Thank you for your Feedback. Yes I see this Point meanwhile. On the other Hand when the subscriber unsubscribes he still has to be aware to get notified and this fact (I hope I'm right on this, that it is a fact) I never found in a discussion.

                Time Publisher Subscriber


                1 Take a copy -
                2 - Unsubscribe
                3 Invoke "Check for race condition needed before proceeding"

                P Offline
                P Offline
                Pete OHanlon
                wrote on last edited by
                #10

                It's not the unsubscribed side that is the problem. If you think about it from the point of view of why you test the event in the first place, it gives you the hint that you could end with functionally identical code between not testing the subscription and throwing an exception because nothing is listening to the event and testing it and throwing an exception because you have ended up in a situation where nothing is listening to the event.

                This space for rent

                1 Reply Last reply
                0
                • B BillWoodruff

                  I think you may find Jon Skeet's comments on this relevant: [^], and his information on using an extension method, and the null-conditional operator in C#6 ... interesting. I don't pretend to understand the thread-safety and/or multiple-subscriber issues involved: for that we need Richard Deeming or Richard MacCutchan to step-up :)

                  «There is a spectrum, from "clearly desirable behaviour," to "possibly dodgy behavior that still makes some sense," to "clearly undesirable behavior." We try to make the latter into warnings or, better, errors. But stuff that is in the middle category you don’t want to restrict unless there is a clear way to work around it.» Eric Lippert, May 14, 2008

                  Richard DeemingR Offline
                  Richard DeemingR Offline
                  Richard Deeming
                  wrote on last edited by
                  #11

                  BillWoodruff wrote:

                  we need Richard Deeming or Richard MacCutchan to step-up :)

                  :-O Or Pete, who nailed the explanation below. But your link also answers the question, albeit in much greater detail.


                  "These people looked deep within my soul and assigned me a number based on the order in which I joined." - Homer

                  "These people looked deep within my soul and assigned me a number based on the order in which I joined" - Homer

                  1 Reply Last reply
                  0
                  • P Pete OHanlon

                    Imagine your system has an event with one subscriber. This subscriber is on a background thread. Now, consider the case where the very last action before context switching over to the thread your subscriber is on is to check to see if you have any subscriptions. That's fine as the null check will tell you that you have a subscriber. Okay, you're now processing on this other thread and the first thing it does is to remove the event subscription. You now have nothing hooked up to the event but when you context switch back, it's going to continue as though there are subscriptions. That's why you take the copy.

                    This space for rent

                    B Offline
                    B Offline
                    BillWoodruff
                    wrote on last edited by
                    #12

                    Pete O'Hanlon wrote:

                    That's why you take the copy.

                    Really appreciate your explanation, Pete ! From what you say, I infer that when you do something like: var handler = PropertyChanged; Then an actual copy of the underlying handler is made ? Not just a "duplicate of the pointer" ? My struggle to form some kind of practically useful "mental model" of EventHandlers and InvocationQueue ... continues, although I don't have any real problem using them, right now ... albeit my usage does not include dealing with possible threading issues, yet. What saved my read-end was learning that you can effectively switch a specific EventHandler instance in/out by doing a -= remove call which, praise be, does not throw an error if the EventHandler == null. From now on, I believe I can summon your presence by simply invoking the names of the two Richards :)

                    «There is a spectrum, from "clearly desirable behaviour," to "possibly dodgy behavior that still makes some sense," to "clearly undesirable behavior." We try to make the latter into warnings or, better, errors. But stuff that is in the middle category you don’t want to restrict unless there is a clear way to work around it.» Eric Lippert, May 14, 2008

                    Richard DeemingR L 2 Replies Last reply
                    0
                    • B BillWoodruff

                      Pete O'Hanlon wrote:

                      That's why you take the copy.

                      Really appreciate your explanation, Pete ! From what you say, I infer that when you do something like: var handler = PropertyChanged; Then an actual copy of the underlying handler is made ? Not just a "duplicate of the pointer" ? My struggle to form some kind of practically useful "mental model" of EventHandlers and InvocationQueue ... continues, although I don't have any real problem using them, right now ... albeit my usage does not include dealing with possible threading issues, yet. What saved my read-end was learning that you can effectively switch a specific EventHandler instance in/out by doing a -= remove call which, praise be, does not throw an error if the EventHandler == null. From now on, I believe I can summon your presence by simply invoking the names of the two Richards :)

                      «There is a spectrum, from "clearly desirable behaviour," to "possibly dodgy behavior that still makes some sense," to "clearly undesirable behavior." We try to make the latter into warnings or, better, errors. But stuff that is in the middle category you don’t want to restrict unless there is a clear way to work around it.» Eric Lippert, May 14, 2008

                      Richard DeemingR Offline
                      Richard DeemingR Offline
                      Richard Deeming
                      wrote on last edited by
                      #13

                      As I understand it, it's a "duplicate of the pointer", not a deep clone of the delegate. When you add or remove a handler, the "pointer" is replaced with a new instance, because delegates are immutable.

                      Delegate Class (System)[^]:

                      Delegates are immutable; once created, the invocation list of a delegate does not change. ... Combining operations, such as Combine and Remove, do not alter existing delegates. Instead, such an operation returns a new delegate that contains the results of the operation, an unchanged delegate, or null.

                      Again, Jon Skeet has some good information: C# in Depth: Delegates and Events[^]


                      "These people looked deep within my soul and assigned me a number based on the order in which I joined." - Homer

                      "These people looked deep within my soul and assigned me a number based on the order in which I joined" - Homer

                      1 Reply Last reply
                      0
                      • B BillWoodruff

                        Pete O'Hanlon wrote:

                        That's why you take the copy.

                        Really appreciate your explanation, Pete ! From what you say, I infer that when you do something like: var handler = PropertyChanged; Then an actual copy of the underlying handler is made ? Not just a "duplicate of the pointer" ? My struggle to form some kind of practically useful "mental model" of EventHandlers and InvocationQueue ... continues, although I don't have any real problem using them, right now ... albeit my usage does not include dealing with possible threading issues, yet. What saved my read-end was learning that you can effectively switch a specific EventHandler instance in/out by doing a -= remove call which, praise be, does not throw an error if the EventHandler == null. From now on, I believe I can summon your presence by simply invoking the names of the two Richards :)

                        «There is a spectrum, from "clearly desirable behaviour," to "possibly dodgy behavior that still makes some sense," to "clearly undesirable behavior." We try to make the latter into warnings or, better, errors. But stuff that is in the middle category you don’t want to restrict unless there is a clear way to work around it.» Eric Lippert, May 14, 2008

                        L Offline
                        L Offline
                        Lost User
                        wrote on last edited by
                        #14

                        I had the same question and so I made a test. In this test I made a copy of the handler as suggested var handler = PropertyChanged;, then let remove the handler from the subscriber (-=) and see, handler still holds the copied subscription(s). So here copy means more Clone I think. I hope it helps :)

                        M 1 Reply Last reply
                        0
                        • L Lost User

                          I had the same question and so I made a test. In this test I made a copy of the handler as suggested var handler = PropertyChanged;, then let remove the handler from the subscriber (-=) and see, handler still holds the copied subscription(s). So here copy means more Clone I think. I hope it helps :)

                          M Offline
                          M Offline
                          Maarten1977
                          wrote on last edited by
                          #15

                          The delegate is immutable. So handler -= someHandler; is not modifying or updating the original delegate, it is creating a new delegate which is then stored in handler. So the copy-of-the-handler is indeed a copy of the reference to the (immutable) delegate.

                          L 1 Reply Last reply
                          0
                          • M Maarten1977

                            The delegate is immutable. So handler -= someHandler; is not modifying or updating the original delegate, it is creating a new delegate which is then stored in handler. So the copy-of-the-handler is indeed a copy of the reference to the (immutable) delegate.

                            L Offline
                            L Offline
                            Lost User
                            wrote on last edited by
                            #16

                            Thank you very much for the this reply :thumbsup:

                            1 Reply Last reply
                            0
                            Reply
                            • Reply as topic
                            Log in to reply
                            • Oldest to Newest
                            • Newest to Oldest
                            • Most Votes


                            • Login

                            • Don't have an account? Register

                            • Login or register to search.
                            • First post
                              Last post
                            0
                            • Categories
                            • Recent
                            • Tags
                            • Popular
                            • World
                            • Users
                            • Groups