none
c# 串口监听程序造成死机蓝屏问题 RRS feed

  • 问题

  • 我写了一个小程序用于监听串口的数据,第一次点监听,然后暂停,都还正常,但是再点监听的时候就会造成蓝屏死机.我是在虚拟机里面用SerialNull 模拟的串口通信,用别的测试软件通信正常.串口消息是用测试软件发的,监听正常,但是就是在暂停和监听切换的时候会造成蓝屏死机。请大家帮帮忙看看问题在哪里。
    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.Text;
    using System.Windows.Forms;
    using System.IO.Ports;
    using System.Threading;


    namespace PortTest
    {
    public partial class Form1 : Form
    {
    public Form1()
    {
    InitializeComponent();
    }

    private SerialPort Sp = new SerialPort();
    public delegate void SetTextCallback(string text);
    private Thread newThread = null;
    string readstr = null;

    private void SetText(string text)
    {
    if (this.textBox_data.InvokeRequired)
    {
    SetTextCallback d = new SetTextCallback(SetText);
    this.Invoke(d, new object[] { text });
    }
    else
    {
    this.textBox_data.Text = text;
    }

    }
    private void ThreadProcSafe()
    {
    this.SetText(readstr);
    }
    public void Sp_DataReceived(object sender,System.IO.Ports.SerialDataReceivedEventArgs e)
    {
    byte[] readBuffer = new byte[Sp.ReadBufferSize];
    Sp.Read(readBuffer, 0, readBuffer.Length);
    readstr =Encoding.UTF8.GetString(readBuffer);


    this.newThread = new Thread(new ThreadStart(this.ThreadProcSafe));
    this.newThread.Start();
    }

    private void button1_Click(object sender, EventArgs e)
    {
    Sp.PortName = "COM4";
    Sp.BaudRate = 9600;
    Sp.Parity = Parity.None;
    Sp.StopBits = StopBits.One;

    Sp.DataReceived += new SerialDataReceivedEventHandler(Sp_DataReceived);
    Sp.ReceivedBytesThreshold = 1;
    try
    {
    Sp.Open();
    button_pause.Enabled = true;
    button_listen.Enabled = false;
    }
    catch
    {
    MessageBox.Show("端口COM4打开失败!");
    }
    }
    private void button2_Click(object sender, EventArgs e)
    {
    newThread.Abort();
    Sp.Close();
    button_listen.Enabled = true;
    button_pause.Enabled = false;
    }
    }
    }
    2010年3月22日 3:05