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
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.
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
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.