简体   繁体   中英

C# How to create a Singleton that publishes events & Classes that subscribe?

Goal: Have a singleton publish events and allow any class to subscribe/listen to those events

Problem: I cannot figure out how to do this. The code below is illegal but it purveys what I'm trying to do

TransmitManager Class - Publisher

    //Singleton
    public sealed class TransmitManager
    {

        delegate void TransmitManagerEventHandler(object sender);
        public static event TransmitManagerEventHandler OnTrafficSendingActive;
        public static event TransmitManagerEventHandler OnTrafficSendingInactive;

        private static TransmitManager instance = new TransmitManager();



        //Singleton
        private TransmitManager()
        {

        }

        public static TransmitManager getInstance()
        {
            return instance;
        }

        public void Send()
        {
           //Invoke Event
           if (OnTrafficSendingActive != null)
              OnTrafficSendingActive(this);

          //Code connects & sends data

          //Invoke idle event
          if (OnTrafficSendingInactive != null)
            OnTrafficSendingInactive(this);

       }
   }

Test Class - Event Subscriber

   public class Test
   {

     TrasnmitManager tm = TransmitManager.getInstance();

     public Test()
     {
        //I can't do this below. What should my access level be to able to do this??

        tm.OnTrafficSendingActive += new TransmitManagerEventHandler(sendActiveMethod);

     }

     public void sendActiveMethod(object sender)
     {

        //do stuff to notify Test class a "send" event happend
     }
  }

You shouldn't need to make the events static .

public event TransmitManagerEventHandler OnTrafficSendingActive;
public event TransmitManagerEventHandler OnTrafficSendingInactive;

Either your events have to be instance members or you have to address them as static.

TransmitManager.OnTrafficSendingActive +=...

OR

public event TransmitManagerEventHandler OnTrafficSendingActive;

...

TransmitManager.Instance.OnTrafficSendingActive+=...

Also: use EventHandler as your event delegate. Consider making a custom arguments class and pass the status to just one event instead of multiple events. This will let you pass status messages as well.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM