日期:2014-05-17  浏览次数:20833 次

.net SerialPort Close()导致程序被挂起!
private SerialPort Sp = new SerialPort();
  public delegate void HandleInterfaceUpdataDelegate(string text);
  private HandleInterfaceUpdataDelegate interfaceUpdataHandle;
Sp.Close();
  Sp.PortName = Common.BaseClass.strCom;
  Sp.BaudRate = 9600;
  Sp.Parity = Parity.None;
  Sp.RtsEnable = false;
  Sp.DataBits = 8;
  Sp.StopBits = StopBits.One;
  Sp.ReceivedBytesThreshold = 100;
  Sp.ReadTimeout = 200;
  Sp.DataReceived += new SerialDataReceivedEventHandler(Sp_DataReceived);
  interfaceUpdataHandle = new HandleInterfaceUpdataDelegate(UpdateTextBox);//实例化委托对象
  if (Sp.IsOpen == true) Sp.Close();
  try
  {
  Sp.Open();
  bolFlag = true;
  }
  catch
  {
  MessageBox.Show("端口" + Common.BaseClass.strCom + "打开失败!");
  }


在离开该页面时需要关闭串口
Sp.Close()
有的时候程序运行Sp.Close()时会导致应用程序被挂起hungapp(错误提示在window日志中)!为什么啊!什么办法都想过了就是不行啊!
哪位大哥大姐帮帮忙啊!急急急急急!!!!!!

------解决方案--------------------
执行 DataReceived 时间后 ,执行以下Invoke

try
{
byte[] readBuffer = new byte[sp.ReadBufferSize];
//byte[] readBuffer = new byte[3];

Thread.Sleep(1000); //做一个延时,否则分两次发送
sp.Read(readBuffer, 0, readBuffer.Length);

this.Invoke(interfaceUpdataHandle, new string[] { Encoding.UTF8.GetString(readBuffer) });

}
catch (Exception ex)
{
MessageBox.Show("发生错误:" + ex.ToString());
}