串口读数关闭不掉问题
我的目的是,单机按钮,调用Main1()方法取数,然后给textbox赋值,一直开着怕对程序压力大,就关掉了。我在自己电脑上调试一点问题没有,将debug文件换了台电脑时运行发现,当我点击2次按钮时会报Access to the port 'COM1' is denied,这个错误,后来我加上弹窗之后发现一直在弹窗,也就是说mySerialPort.close();方法失效,换成mySerialPort.Dispose();也不可以,请问这是怎么回事。下面代码
SerialPort mySerialPort = null;
/开启端口
public void Main1()
{
mySerialPort = new SerialPort("COM2");
mySerialPort.BaudRate = 9600;
mySerialPort.Parity = Parity.None;
mySerialPort.StopBits = StopBits.One;
mySerialPort.DataBits = 8;
mySerialPort.Handshake = Handshake.None;
mySerialPort.DataReceived += new SerialDataReceivedEventHandler(DataReceivedHandler);
mySerialPort.Open();
}
//读取数据
private void DataReceivedHandler(object sender, SerialDataReceivedEventArgs e)
{
SerialPort sp = (SerialPort)sender;
string indata = sp.ReadExisting();
if (indata.Contains("*0") && indata.Contains("0\r"))
{
mySerialPort.Close();
string zfc = indata.Replace("*0", "$");
string[] sz = zfc.Split('$');
string xxx = sz[1].Replace("0\r", "!");
string[] sz2 = xxx.Split('!');
MessageBox.Show(sz2[0].Trim());//此处加的弹窗
SetText(sz2[0].Trim());
}
}
//textbox赋值
private delegate void SetTextCallback(string text);
private void SetText(string text)
{
// InvokeRequired需要比较调用线程ID和创建线程ID
// 如果它们不相同则返回true
if (this.textBox2.InvokeRequired)
{
SetTextCallback d = new SetTextCallback(SetText);
this.Invoke(d, new object[] { text });
}
else
{
this.textBox2.Text = text;
}
}