I am using serial port communications in my ASP.NET webform application:
private bool sendSMS(int portNo, string mobNo, string details)
{
try
{
SerialPort SerialPort1 = new SerialPort();
SerialPort1.PortName = "COM" + portNo.ToString();
SerialPort1.BaudRate = 9600;
SerialPort1.Parity = Parity.None;
SerialPort1.DataBits = 8;
SerialPort1.StopBits = StopBits.One;
SerialPort1.RtsEnable = true;
SerialPort1.DtrEnable = true;
SerialPort1.Encoding.GetEncoder();
SerialPort1.ReceivedBytesThreshold = 1;
SerialPort1.NewLine = Environment.NewLine;
SerialPort1.Open();
SerialPort1.Write("AT" + SerialPort1.NewLine);
Sleep(500);
SerialPort1.Write("AT+CMGF=1" + SerialPort1.NewLine);
Sleep(500);
SerialPort1.Write("AT+CMGS=" + (char)34 + mobNo + (char)34 +
SerialPort1.NewLine);
Sleep(1000);
SerialPort1.Write(details + (char)26);
Sleep(2000);
SerialPort1.Close();
}
catch
{
}
return true;
}
This method works when I send in a single message… But when I want to send SMSes in bulk opening and closing port everytime is not a good idea… Is it possible to use a serial port like session in c#?
When I open a port I want it to be open for one hour and then if my time expires I want to close the port and open it the next time… Is it possible?
You could create an object and in its constructor/initialization call
SerialPort.Open()and implement IDisposable to callSerialPort.Close(). For the lifetime of the object, it’ll be open.Something a little more detailed is below (though definitely not a complete solution). The general idea is to encapsulate the port connection lifetime into the object lifetime so that when the object goes out of scope/use and gets cleaned by the GC then so does the port connection.
@jrista makes a good point about needing to handle any error conditions. ErrorReceived will help with that, as well as ol’ fashioned error handling throughout this code where necessary.