我在ASP.NET网络表单应用程序中使用串口通信:
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;
}
当我发送单个消息时此方法有效...但是当我想每次批量发送SMSes批量打开和关闭端口时不是一个好主意...是否可以使用串口喜欢c#中的会话?
当我打开一个端口时,我希望它打开一个小时,然后如果我的时间到期,我想关闭端口并在下次打开它...是否可能?
答案 0 :(得分:3)
您可以创建一个对象,并在其构造函数/初始化调用SerialPort.Open()
中实现IDisposable以调用SerialPort.Close()
。对于对象的生命周期,它将是开放的。
下面有一些更详细的内容(虽然绝对不是一个完整的解决方案)。一般的想法是将端口连接生存期封装到对象生存期中,以便当对象超出范围/使用并被GC清除时,端口连接也是如此。
@jrista对需要处理任何错误条件提出了一个很好的观点。 ErrorReceived将有助于此,以及必要时在整个代码中进行时尚的错误处理。
public class SerialPortConnection : IDisposable
{
private bool disposed;
public SerialPort Port { get; protected set; }
public SerialPortConnection(int portNo)
{
this.Initialize(portNo);
this.Port.ErrorReceived += this.portError;
this.Port.Open();
}
public void Initialize(int portNo)
{
this.Port = new SerialPort();
this.Port.PortName = "COM" + portNo.ToString();
/* snip */
this.Port.Encoding.GetEncoder();
this.Port.ReceivedBytesThreshold = 1;
this.Port.NewLine = Environment.NewLine;
}
protected void portError(
object sender,
SerialErrorReceivedEventHandler args)
{
// Do whatever with the error, maybe need to reopen the socket.
}
protected virtual void Dispose(bool disposing)
{
if (!disposed)
{
if (disposing)
{
this.Port.Close();
this.Port.Dispose(disposing);
}
this.disposed = true;
}
}
public void Dispose()
{
this.Dispose(true);
}
}