Sharing a class between multiple forms

前端 未结 3 755
星月不相逢
星月不相逢 2021-01-23 05:39

I need help figuring this question out. I\'ve tried searching and I think I might have found a solution using a Singleton Design pattern, but want to make sure.

I have a

相关标签:
3条回答
  • 2021-01-23 06:10

    Alternative to @Luiggi's solution, here's one a bit more thread conscience:

    public sealed class SerialPort
    {
      private static volatile SerialPort instance;
      private static object threadLock = new Object();
    
      /// <summary>Retrieve an instance of SerialPort</summary>
      public static SerialPort Instance
      {
        get
        {
          if (SerialPort.instance == null)
          {
            lock (SerialPort.threadLock)
            {
              if (SerialPort.instance == null)
              {
                SerialPort.instance == new Serialport();
              }
            }
          }
          return SerialPort.instance;
        }
      }
    
      private SerialPort(){}
    }
    

    Then, in practice:

    SerialPort sp = SerialPort.Instance;
    sp.MyMethod(...);
    

    More information on this Singleton pattern.

    0 讨论(0)
  • 2021-01-23 06:11

    As you already said, this problem can be solved using the Singleton Design Pattern. Here is a small sample:

    public class MySingleton() {
        private static MySingleton instance = new MySingleton();
    
        //your attributes go here...
        private MySingleton() {
        //your logic goes here...
        }
    
        public static MySingleton getInstance() {
            return instance;
        }
    }
    

    Note that if your static instance will be used for multiple threads, your class should lock the shared resources. I'll let you a reference to Thread Safe Code

    0 讨论(0)
  • 2021-01-23 06:23

    Actually, I've just ran into the same problem yesterday, and I think I might have found a much easier way of approaching this matter instead of using the singleton method. I made a class file and created a class called public class Serial. Inside I declared my serial variable as static SerialPort (i.e. static SerialPort serial); same with a timer if you need to use one. Create a function for set and get called serialStatus, where it sets a public static bool. I really would like to post my code here, but I really don't understand how to properly do it. In your form, you would have the first form start the serial port. For the other form, all you have to do is declare Serial serial = new Serial(); pull out the methods, and you're good to go. If you need to make changes to the serial settings, you can create a method with a bool input (i.e. if true, serial.Close(); then restart serial with new settings.

    0 讨论(0)
提交回复
热议问题