none
Help on Event with multiple subscribers RRS feed

  • Question

  • see my comments inside

        public class Publisher
        {
            public event EventHandler OnCalculation;
    
            public void Calculate()
            {
                if (OnCalculation != null)
                {
                    OnCalculation(this, new EventArgs());
                }
            }
        }
     public class SomeOtherSubscriber
        {
            public void DoSomething()
            {
                Publisher pub1 = new Publisher();
                pub1.OnCalculation += pub1_OnCalculation;
            }
    
            void pub1_OnCalculation(object sender, EventArgs e)
            {
                //if do not get call back here, why ?????
            }
        }
        class Program
        {
            static void Main(string[] args)
            {
                SomeOtherSubscriber sub = new SomeOtherSubscriber();
                sub.DoSomething();
    
                Publisher pub1 = new Publisher();
                pub1.OnCalculation += pub1_OnCalculation;
                pub1.Calculate();
    
                Thread.Sleep(30000);
            }
    
            static void pub1_OnCalculation(object sender, EventArgs e)
            {
              // i get the call back here   
            }
        }
    }



    Thursday, May 8, 2014 9:57 PM

Answers


  • I solved it by creating static event, now doesn't matter who calls Calculate() method, both subscriber gets call back

    • Marked as answer by lax4u Friday, May 9, 2014 6:44 PM
    Friday, May 9, 2014 6:44 PM

All replies

  • "if do not get call back here, why ?????"

    Why would you get a call back there? SomeOtherSubscriber creates a Publisher object, adds an event handler and then never calls Calculate on that object. Of course, that the event is never raised.

    Thursday, May 8, 2014 11:09 PM
    Moderator

  • I solved it by creating static event, now doesn't matter who calls Calculate() method, both subscriber gets call back

    • Marked as answer by lax4u Friday, May 9, 2014 6:44 PM
    Friday, May 9, 2014 6:44 PM
  • Yes, that would work if this is your goal. But be careful with static events, the subscriber must bet disconnected from the event at some point. If it's not disconnected then the subscriber object will never garbage collected because the static event keeps a reference to it.
    Friday, May 9, 2014 8:34 PM
    Moderator
  • how do you disconnect subscriber?
    Tuesday, May 13, 2014 8:39 PM
  • Using -= :

    Publisher.OnCalculation -= pub1_OnCalculation;

    Wednesday, May 14, 2014 5:40 AM
    Moderator