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
CODE PROJECT For Those Who Code
  • Home
  • Articles
  • FAQ
Community
  1. Home
  2. General Programming
  3. C#
  4. delegates and events

delegates and events

Scheduled Pinned Locked Moved C#
csharphtmlcomsysadminhosting
11 Posts 5 Posters 0 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.
  • S staticv

    // Holds the arguments for the StatusChanged event

    public class StatusChangedEventArgs : EventArgs

    {

    // The argument we're interested in is a message describing the event
    
    private string EventMsg;
    
    
    
    // Property for retrieving and setting the event message
    
    public string EventMessage
    
    {
    
        get
    
        {
    
            return EventMsg;
    
        }
    
        set
    
        {
    
            EventMsg = value;
    
        }
    
    }
    
    
    
    // Constructor for setting the event message
    
    public StatusChangedEventArgs(string strEventMsg)
    
    {
    
        EventMsg = strEventMsg;
    
    }
    

    }

    // This delegate is needed to specify the parameters we're passing with our event
    public delegate void StatusChangedEventHandler(object sender, StatusChangedEventArgs e);

    public static event StatusChangedEventHandler StatusChanged; Okay, so in the above code, we created a delegate and a custom event.

    // This is called when we want to raise the StatusChanged event
    
    public static void OnStatusChanged(StatusChangedEventArgs e)
    
    {
    
        **StatusChangedEventHandler statusHandler = StatusChanged;**
    
        if (statusHandler != null)
    
        {
    
            // Invoke the delegate
    
            statusHandler(null, e);
    
        }
    
    }
    

    What does the bold line do? Why do we check for null? EDIT: The code is from C# Chat: Part 2 - Building the Chat Server (C# Programming Tutorial) • Geekpedia[^] check that out, if the above code doesn't provides what I mean.

    Top Web Hosting Providers[^] Do, or do not. There is no 'try'.

    L Offline
    L Offline
    Luc Pattyn
    wrote on last edited by
    #2

    Hi, you make a local copy of StatusChanged, so the same value gets used both in the null-text and the invocation; StatusChanged is public, so it could be changed by another thread at any point in time; removing the last handler from it right after the null-test got executed would cause an exception in statusHandler(null, e); In summary, without it your code would not be thread-safe. :)

    Luc Pattyn [Forum Guidelines] [My Articles]


    - before you ask a question here, search CodeProject, then Google - the quality and detail of your question reflects on the effectiveness of the help you are likely to get - use the code block button (PRE tags) to preserve formatting when showing multi-line code snippets


    modified on Friday, June 10, 2011 12:01 PM

    S J 2 Replies Last reply
    0
    • S staticv

      // Holds the arguments for the StatusChanged event

      public class StatusChangedEventArgs : EventArgs

      {

      // The argument we're interested in is a message describing the event
      
      private string EventMsg;
      
      
      
      // Property for retrieving and setting the event message
      
      public string EventMessage
      
      {
      
          get
      
          {
      
              return EventMsg;
      
          }
      
          set
      
          {
      
              EventMsg = value;
      
          }
      
      }
      
      
      
      // Constructor for setting the event message
      
      public StatusChangedEventArgs(string strEventMsg)
      
      {
      
          EventMsg = strEventMsg;
      
      }
      

      }

      // This delegate is needed to specify the parameters we're passing with our event
      public delegate void StatusChangedEventHandler(object sender, StatusChangedEventArgs e);

      public static event StatusChangedEventHandler StatusChanged; Okay, so in the above code, we created a delegate and a custom event.

      // This is called when we want to raise the StatusChanged event
      
      public static void OnStatusChanged(StatusChangedEventArgs e)
      
      {
      
          **StatusChangedEventHandler statusHandler = StatusChanged;**
      
          if (statusHandler != null)
      
          {
      
              // Invoke the delegate
      
              statusHandler(null, e);
      
          }
      
      }
      

      What does the bold line do? Why do we check for null? EDIT: The code is from C# Chat: Part 2 - Building the Chat Server (C# Programming Tutorial) • Geekpedia[^] check that out, if the above code doesn't provides what I mean.

      Top Web Hosting Providers[^] Do, or do not. There is no 'try'.

      D Offline
      D Offline
      DaveyM69
      wrote on last edited by
      #3

      Luc's answer is perfect. In addition, there's no need to declare your own delegate (from 2.0 onwards). Instead, just declare the event... public event EventHandler<StatusChangedEventArgs> StatusChanged; and in the OnStatusChanged... EventHandler<StatusChangedEventArgs> statusHandler = StatusChanged;

      Dave
      BTW, in software, hope and pray is not a viable strategy. (Luc Pattyn)
      Visual Basic is not used by normal people so we're not covering it here. (Uncyclopedia)

      L 1 Reply Last reply
      0
      • L Luc Pattyn

        Hi, you make a local copy of StatusChanged, so the same value gets used both in the null-text and the invocation; StatusChanged is public, so it could be changed by another thread at any point in time; removing the last handler from it right after the null-test got executed would cause an exception in statusHandler(null, e); In summary, without it your code would not be thread-safe. :)

        Luc Pattyn [Forum Guidelines] [My Articles]


        - before you ask a question here, search CodeProject, then Google - the quality and detail of your question reflects on the effectiveness of the help you are likely to get - use the code block button (PRE tags) to preserve formatting when showing multi-line code snippets


        modified on Friday, June 10, 2011 12:01 PM

        S Offline
        S Offline
        staticv
        wrote on last edited by
        #4

        so the same value gets used both in the null-text and the invocation; I'm sorry, but I didn't got it, what do you mean by null-text and the invocation? I'm converting this code to C++/CLI so I don't know C#, that's why having little problems... :)

        Top Web Hosting Providers[^] Do, or do not. There is no 'try'.

        L 1 Reply Last reply
        0
        • S staticv

          // Holds the arguments for the StatusChanged event

          public class StatusChangedEventArgs : EventArgs

          {

          // The argument we're interested in is a message describing the event
          
          private string EventMsg;
          
          
          
          // Property for retrieving and setting the event message
          
          public string EventMessage
          
          {
          
              get
          
              {
          
                  return EventMsg;
          
              }
          
              set
          
              {
          
                  EventMsg = value;
          
              }
          
          }
          
          
          
          // Constructor for setting the event message
          
          public StatusChangedEventArgs(string strEventMsg)
          
          {
          
              EventMsg = strEventMsg;
          
          }
          

          }

          // This delegate is needed to specify the parameters we're passing with our event
          public delegate void StatusChangedEventHandler(object sender, StatusChangedEventArgs e);

          public static event StatusChangedEventHandler StatusChanged; Okay, so in the above code, we created a delegate and a custom event.

          // This is called when we want to raise the StatusChanged event
          
          public static void OnStatusChanged(StatusChangedEventArgs e)
          
          {
          
              **StatusChangedEventHandler statusHandler = StatusChanged;**
          
              if (statusHandler != null)
          
              {
          
                  // Invoke the delegate
          
                  statusHandler(null, e);
          
              }
          
          }
          

          What does the bold line do? Why do we check for null? EDIT: The code is from C# Chat: Part 2 - Building the Chat Server (C# Programming Tutorial) • Geekpedia[^] check that out, if the above code doesn't provides what I mean.

          Top Web Hosting Providers[^] Do, or do not. There is no 'try'.

          G Offline
          G Offline
          Giorgi Dalakishvili
          wrote on last edited by
          #5

          Here is a very good article about events: C# Event Implementation Fundamentals, Best Practices and Conventions[^]

          Giorgi Dalakishvili #region signature My Articles Asynchronous Registry Notification Using Strongly-typed WMI Classes in .NET [^] My blog #endregion

          1 Reply Last reply
          0
          • L Luc Pattyn

            Hi, you make a local copy of StatusChanged, so the same value gets used both in the null-text and the invocation; StatusChanged is public, so it could be changed by another thread at any point in time; removing the last handler from it right after the null-test got executed would cause an exception in statusHandler(null, e); In summary, without it your code would not be thread-safe. :)

            Luc Pattyn [Forum Guidelines] [My Articles]


            - before you ask a question here, search CodeProject, then Google - the quality and detail of your question reflects on the effectiveness of the help you are likely to get - use the code block button (PRE tags) to preserve formatting when showing multi-line code snippets


            modified on Friday, June 10, 2011 12:01 PM

            J Offline
            J Offline
            jkohler
            wrote on last edited by
            #6

            Isn't that just making a copy of the reference? And therefore no safer than testing/invoking directly on the original reference?

            Subvert The Dominant Paradigm -- bumper sticker, circa 1971

            L 1 Reply Last reply
            0
            • S staticv

              so the same value gets used both in the null-text and the invocation; I'm sorry, but I didn't got it, what do you mean by null-text and the invocation? I'm converting this code to C++/CLI so I don't know C#, that's why having little problems... :)

              Top Web Hosting Providers[^] Do, or do not. There is no 'try'.

              L Offline
              L Offline
              Luc Pattyn
              wrote on last edited by
              #7

              :confused: :confused:

              if (statusHandler != null) <--- that looks like a null-test
              // Invoke the delegate
              statusHandler(null, e); <--- according to the comment this is an invocation

              :)

              Luc Pattyn [Forum Guidelines] [My Articles]


              - before you ask a question here, search CodeProject, then Google - the quality and detail of your question reflects on the effectiveness of the help you are likely to get - use the code block button (PRE tags) to preserve formatting when showing multi-line code snippets


              modified on Friday, June 10, 2011 12:02 PM

              S 1 Reply Last reply
              0
              • D DaveyM69

                Luc's answer is perfect. In addition, there's no need to declare your own delegate (from 2.0 onwards). Instead, just declare the event... public event EventHandler<StatusChangedEventArgs> StatusChanged; and in the OnStatusChanged... EventHandler<StatusChangedEventArgs> statusHandler = StatusChanged;

                Dave
                BTW, in software, hope and pray is not a viable strategy. (Luc Pattyn)
                Visual Basic is not used by normal people so we're not covering it here. (Uncyclopedia)

                L Offline
                L Offline
                Luc Pattyn
                wrote on last edited by
                #8

                :rose:

                Luc Pattyn [Forum Guidelines] [My Articles]


                - before you ask a question here, search CodeProject, then Google - the quality and detail of your question reflects on the effectiveness of the help you are likely to get - use the code block button (PRE tags) to preserve formatting when showing multi-line code snippets


                1 Reply Last reply
                0
                • L Luc Pattyn

                  :confused: :confused:

                  if (statusHandler != null) <--- that looks like a null-test
                  // Invoke the delegate
                  statusHandler(null, e); <--- according to the comment this is an invocation

                  :)

                  Luc Pattyn [Forum Guidelines] [My Articles]


                  - before you ask a question here, search CodeProject, then Google - the quality and detail of your question reflects on the effectiveness of the help you are likely to get - use the code block button (PRE tags) to preserve formatting when showing multi-line code snippets


                  modified on Friday, June 10, 2011 12:02 PM

                  S Offline
                  S Offline
                  staticv
                  wrote on last edited by
                  #9

                  Hmmm, you wrote null-text :) lol.. Thanks anyways

                  Top Web Hosting Providers[^] Do, or do not. There is no 'try'.

                  1 Reply Last reply
                  0
                  • J jkohler

                    Isn't that just making a copy of the reference? And therefore no safer than testing/invoking directly on the original reference?

                    Subvert The Dominant Paradigm -- bumper sticker, circa 1971

                    L Offline
                    L Offline
                    Luc Pattyn
                    wrote on last edited by
                    #10

                    Yes, it copies a reference, making sure the event and the delegates inside it can not be garbage collected (it is a local copy). There still is a possibility that the event gets changed (it is kind of a linked list), to cope with that you could (probably should) add a try-catch around the invocation. This is one of those rare cases where an empty catch block would be fine: after all, if another thread is allowed to remove the last delegate, that really means there is no need to call it anymore. Have a look at the fine article Giorgi provided. :)

                    Luc Pattyn [Forum Guidelines] [My Articles]


                    - before you ask a question here, search CodeProject, then Google - the quality and detail of your question reflects on the effectiveness of the help you are likely to get - use the code block button (PRE tags) to preserve formatting when showing multi-line code snippets


                    modified on Friday, June 10, 2011 12:02 PM

                    J 1 Reply Last reply
                    0
                    • L Luc Pattyn

                      Yes, it copies a reference, making sure the event and the delegates inside it can not be garbage collected (it is a local copy). There still is a possibility that the event gets changed (it is kind of a linked list), to cope with that you could (probably should) add a try-catch around the invocation. This is one of those rare cases where an empty catch block would be fine: after all, if another thread is allowed to remove the last delegate, that really means there is no need to call it anymore. Have a look at the fine article Giorgi provided. :)

                      Luc Pattyn [Forum Guidelines] [My Articles]


                      - before you ask a question here, search CodeProject, then Google - the quality and detail of your question reflects on the effectiveness of the help you are likely to get - use the code block button (PRE tags) to preserve formatting when showing multi-line code snippets


                      modified on Friday, June 10, 2011 12:02 PM

                      J Offline
                      J Offline
                      jkohler
                      wrote on last edited by
                      #11

                      ahhh... reference to empty versus null reference. Got it. Now I have to rework a whole bunch of code... I foresee a generic solution

                      Subvert The Dominant Paradigm -- bumper sticker, circa 1971

                      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