【发布时间】:2016-07-08 17:34:27
【问题描述】:
我编写了以下代码来配置 MainForm 加载时的串行端口。在第一次运行时,它会在端口打开时给出IOException,说明参数不正确。但是当我重新启动应用程序时,它工作正常。只有在启动计算机后第一次运行应用程序时才会出现异常,然后它可以正常工作,直到下次重新启动计算机。
private void Main_Load(object sender, EventArgs e)
{
this.serialPort1.PortName = "COM3";
this.serialPort1.BaudRate = 9600;
this.serialPort1.DataBits = 8;
this.serialPort1.DataReceived += new System.IO.Ports.SerialDataReceivedEventHandler(serialPort1_DataReceived);
this.serialPort1.Open(); //Exception comes here
this.serialPort1.WriteLine("AT#cid=1" + System.Environment.NewLine);
}
例外详情:
System.IO.IOException 未被用户代码处理
Message="参数不正确。\r\n" 来源="系统"
堆栈跟踪: 在 System.IO.Ports.InternalResources.WinIOError(Int32 错误代码,字符串 str) 在 System.IO.Ports.InternalResources.WinIOError() 在 System.IO.Ports.SerialStream.set_RtsEnable(布尔值) 在 System.IO.Ports.SerialStream..ctor (字符串端口名称,Int32 波特率,奇偶校验,Int32 数据位,StopBits stopBits,Int32 读取超时,Int32 写入超时,握手握手,布尔 dtrEnable,布尔 rtsEnable,布尔丢弃空,字节奇偶校验替换) 在 System.IO.Ports.SerialPort.Open() 在 D:\Project\JKamdar\JKamdar\Main.cs:line 264 中的 JKamdar.Main.Main_Load(Object sender, EventArgs e) 在 System.Windows.Forms.Form.OnLoad(EventArgs e) 在 System.Windows.Forms.Form.OnCreateControl() 在 System.Windows.Forms.Control.CreateControl(布尔 fIgnoreVisible) 在 System.Windows.Forms.Control.CreateControl() 在 System.Windows.Forms.Control.WmShowWindow(消息和 m) 在 System.Windows.Forms.Control.WndProc(消息和 m) 在 System.Windows.Forms.ScrollableControl.WndProc(消息和 m) 在 System.Windows.Forms.ContainerControl.WndProc(消息和 m) 在 System.Windows.Forms.Form.WmShowWindow(消息和 m) 在 System.Windows.Forms.Form.WndProc(消息和 m) 在 System.Windows.Forms.Control.ControlNativeWindow.OnMessage(消息& m) 在 System.Windows.Forms.Control.ControlNativeWindow.WndProc(消息和 m) 在 System.Windows.Forms.NativeWindow.Callback(IntPtr hWnd,Int32 msg,IntPtr wparam,IntPtr lparam) 内部异常:
【问题讨论】:
-
能否获取完整的异常信息和堆栈跟踪信息?
-
通过设备管理器检查波特率可能是个问题(只是猜测)
-
@V4Vendetta:最大端口速度 460800
-
@Niraj:什么操作系统?你能在其他操作系统上检查一下,看看哪些受到影响吗?
-
设置 this.serialPort1.RtsEnable = true 并试一试
标签: c# .net serial-port