c#为什么我的串口关闭不关闭端口?

时间:2016-09-21 04:04:23

标签: c# visual-studio

我在serialport.close遇到问题。

Port opened at 9/21/2016 10:58:32 AM
Port communication has been closed 9/21/2016 10:58:48 AM
Access to the port 'COM3' is denied.

一开始我点击连接按钮,第二个我单击断开按钮,在按钮内我填写close.port代码。但是当我再次点击连接时,状态被拒绝。这是我的代码:

public void ClosePort()
{
    if (comPort.IsOpen)
    {
        //e.Cancel = true; //cancel the fom closing
        Thread CloseDown = new Thread(new ThreadStart(CloseSerialOnExit)); //close port in new thread to avoid hang
        CloseDown.Start(); //close port in new thread to avoid hang
        DisplayData(MessageType.Error, "Port communication has been closed" + " " + DateTime.Now + "\n");
    }
}

private void CloseSerialOnExit()
{
    try
    {
        comPort.Close(); //close the serial port
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message); //catch any serial port closing error messages
    }
    BeginInvoke(new EventHandler(NowClose)); //now close back in the main thread
}

private void NowClose(object sender, EventArgs e)
{
    comPort.Close(); //now close the form
}

public void BeginInvoke(Delegate method)
{ 

}        

此代码显示要关闭的消息成功,但是当再次单击connect时访问被拒绝,当我在单击退出按钮时检查任务管理器程序仍在运行时。为什么关闭端口没有响应?是解决这个问题的方法吗?还是用另一种方法?我希望得到建议,非常感谢您的回答和解决方案。

0 个答案:

没有答案