使SerialPort关闭并在关闭窗口时停止读取数据

时间:2015-03-17 10:29:48

标签: c# wpf port

我认为当SerialPort打开时关闭我的WPF窗口时出现问题(我猜它仍会收到一些数据)。什么是关闭它的最佳方法?到目前为止,我找到了解决方案,但不确定它是否有效。

我的SerialPort设置:

                    serialPort.ReadTimeout = 1000;
                    serialPort = new SerialPort();
                    serialPort.PortName = Application.Current.Properties["DevPort"].ToString();
                    serialPort.BaudRate = 9600;
                    serialPort.StopBits = StopBits.One;
                    serialPort.DataBits = 8;
                    serialPort.Parity = Parity.None;
                    serialPort.Handshake = Handshake.None;
                    serialPort.DataReceived += serial_sp_DataReceived;
                    serialPort.Open();

Window.Closing方法:

  if (serialPort.IsOpen)
        {
            this.Closing -= Window_Closing;
            Thread CloseDown = new Thread(new ThreadStart(serialPort.Dispose));
            CloseDown.Start();
        }

很难达到窗口冻结(通常是1x / 10h或更长时间)。在窗口关闭之前关闭/处理serialPort的最佳方法是什么?

@EDIT:

data_received方法:

   int count = serialPort.BytesToRead;
                byte[] ByteArray = new byte[count];
                serialPort.Read(ByteArray, 0, count);
                ByteArray = SubArray(ByteArray, 5, 5);

                string s2 = BitConverter.ToString(ByteArray);

                String[] tempAry = s2.Split('-');
                byte[] decBytes2 = new byte[tempAry.Length];
                for (int i = 0; i < tempAry.Length; i++)
                    decBytes2[i] = Convert.ToByte(tempAry[i], 16);

                string host;
                int port = int.Parse(Application.Current.Properties["Port"].ToString());
                host = Application.Current.Properties["Host"].ToString();
                tekst = s2.Replace("-", "");
                string result = StartClient(host, port, tekst);

                string[] _result = result.Split('_');
                tekst = "";
                if (_result[1].ToString() == "-1")
                {
                    var thread = new Thread(new ThreadStart(ShowError));

                    thread.SetApartmentState(ApartmentState.STA);
                    thread.Start();
                    thread.Join();
                    tekst = "";
                    return;
                }
                card = _result[0];
                points = decimal.Parse(_result[1]);

                thread1 = new Thread(() => pressButton(CardButton));

                thread1.SetApartmentState(ApartmentState.STA);
                thread1.Start();
                thread1.Join();


ShowError method just shows my custom error window. PressButton method raises    b.RaiseEvent(new RoutedEventArgs(Button.ClickEvent));

2 个答案:

答案 0 :(得分:0)

您的问题非常通用:如何在某些线程仍在运行时关闭应用程序?答案非常明显:要求线程关闭,等待它们真正结束。

但是,您的具体问题可能与如何处理SerialPort有关。那是因为它利用了底层线程,你应该注意尽可能地运行它(也就是说,避免任何阻塞)。

典型的情况是当您使用Read方法时,它会阻止流,直到读取所有需要的数据: https://msdn.microsoft.com/en-us/library/ms143549(v=vs.110).aspx

相反,您应该使用另一种方法:首先查看已接收的字节数,然后再读取它们。您的代码应收集总流: https://msdn.microsoft.com/en-us/library/system.io.ports.serialport.bytestoread(v=vs.110).aspx

看看我的一个例子,旧的,但仍然很好: http://cetdevelop.codeplex.com/SourceControl/latest#V2/Cet/IO/Cet.IO.Serial/SerialPortClient.cs

答案 1 :(得分:0)

一旦数据读取完成,您应该考虑处理串行端口实例。在您收到的数据中考虑类似“流结束”标记的内容。当你得到它,配置串口。