locked
event and delegate RRS feed

  • Question

  • User527076549 posted
      public class Alert
        {
            public event EventHandler<EventArgs> SendMessage;
    
            public void Execute()
            {
                SendMessage(this, new EventArgs());
            }
        }
    
        public class Subscriber
        {
            Alert alert = new Alert();
            public void Subscribe()
            {
                alert.SendMessage += (sender, e) => { Console.Write("First"); };
                alert.SendMessage += (sender, e) => { Console.WriteLine("Second"); };
                alert.SendMessage += (sender, e) => { Console.WriteLine("Third"); };
                alert.SendMessage += (sender, e) => { Console.WriteLine("Third"); };
            }
    
            public void Execute()
            {
                alert.Execute();
            }
        }
    
      Subscriber subscriber = new Subscriber();
                subscriber.Subscribe();
                subscriber.Execute();

    Can any one tell me what is the order,in which it get executed ??

    i assume its gives the result in the order its added.

    [p.S question from 70-483 : some one said ,The methods in a delegate are not guaranteed to be called in the same order as they were added.]

    Monday, September 16, 2019 6:41 AM

Answers

  • User541108374 posted

    Hi,

    a quick dotnetfiddle.net (https://dotnetfiddle.net/FOO0NY) shows that they're coming in in the same order. It's however event based so it's not guaranteed that it'll arrive in the same order and if your code depends on the order then use an alternative strategy.

    Kris.

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Monday, September 16, 2019 7:52 AM

All replies

  • User541108374 posted

    Hi,

    a quick dotnetfiddle.net (https://dotnetfiddle.net/FOO0NY) shows that they're coming in in the same order. It's however event based so it's not guaranteed that it'll arrive in the same order and if your code depends on the order then use an alternative strategy.

    Kris.

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Monday, September 16, 2019 7:52 AM
  • User753101303 posted

    Hi,

    Do you really event have to depend on that ? I would ,say that if the ordering of two events matter it likely means they should be actually a single event so that you have explicit control of what you want to happen first....

    Monday, September 16, 2019 8:32 AM