blinky
Member
- Joined
- Oct 21, 2020
- Messages
- 7
- Programming Experience
- Beginner
I have a class that creates and opens a serial port:
I then call the GetObservatoryComPort method to create the object:
The problem I have is that if the user clicks the connect button again, I create 2 instances of the ObservatoryComPort - how can I stop this happening? I want something like if ObservatoryComPort exists!
C#:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO.Ports;
namespace ObservatoryControl
{
public static class ObservatoryPortProvider
{
private static SerialPort ObservatoryCompPort = null;
public static SerialPort GetObservatoryComPort(string SelectedComPort)
{
if (ObservatoryCompPort == null)
{
ObservatoryCompPort = new SerialPort();
ObservatoryCompPort.PortName = SelectedComPort;
ObservatoryCompPort.Open();
}
return ObservatoryCompPort;
}
public static void CloseObservatoryComPort()
{
if (ObservatoryCompPort != null)
{
ObservatoryCompPort.close(); //I'm just guessing there is close method
ObservatoryCompPort = null;
}
}
}
}
I then call the GetObservatoryComPort method to create the object:
C#:
private void BtnConnect_Click(object sender, EventArgs e)
{
string SelectedComPort = (string)ListBoxSerialPorts.SelectedItem;
ObservatoryComPort = ObservatoryPortProvider.GetObservatoryComPort(SelectedComPort);
if (ObservatoryComPort.IsOpen) {
MyTimer.Interval = 1000;
MyTimer.Tick += new EventHandler(MyTimer_Tick);
MyTimer.Start();
}
}
The problem I have is that if the user clicks the connect button again, I create 2 instances of the ObservatoryComPort - how can I stop this happening? I want something like if ObservatoryComPort exists!