通信串口中报ObjectDisposedException错误时怎么解决

今天做项目,做连接硬件的部分。

我要连接三个硬件。

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using ESRI.ArcGIS.Carto;
using System.IO.Ports;//取电脑中串口
using System.Collections;//数组
using System.Threading;
using System.Diagnostics;


namespace Hydor1
{
    public partial class Sounder : Form
    {
        
        string project = String.Empty;
        Boolean isConn = false;
        private SerialPort port1;

        public Sounder(string pro, Boolean conn, SerialPort port)
        {
            InitializeComponent();
            project = pro.Substring(6);//取前六位
            isConn = conn;
            this.port1 = port;
        }
        #region 窗口加载
        private void Depthfinder_Load(object sender, EventArgs e)
        {
            if (isConn)
            {
                Dep_test.Enabled = false;
            }
            else
            {
                Dep_test.Enabled = true;
            }
            //从电脑中查找可用串口
           /* string[] portlist = SerialPort.GetPortNames();//获取当前计算机的串行端口名称数组
            ArrayList comList = new ArrayList();
            for (int i = 0; i < portlist.Length; i++)
            {
                comList.Add(new DictionaryEntry(portlist[i].Substring(3), portlist[i]));
            }
            this.Dep_portName.DataSource = comList;
            this.Dep_portName.DisplayMember = "Value";
            this.Dep_portName.ValueMember = "Key";
           */
            //读取项目数据
            try
            {
                string sql = "select * from Sounder where 项目名称='" + project + "'";
                DataBaseConnection connection = new DataBaseConnection();
                DataSet myds = connection.getDataSet(sql);
                Dep_portName.Text = myds.Tables[0].Rows[0]["测深仪串口"].ToString();
                Dep_parity.Text = myds.Tables[0].Rows[0]["测深仪奇偶校验"].ToString();
                Dep_baudRate.Text = myds.Tables[0].Rows[0]["测深仪波特率"].ToString();
                Dep_stopBits.Text = myds.Tables[0].Rows[0]["测深仪停止位"].ToString();
                Dep_dataBits.Text = myds.Tables[0].Rows[0]["测深仪数据位"].ToString();
                Dep_protocol.Text = myds.Tables[0].Rows[0]["测深仪握手协议"].ToString();
            }
            catch (Exception ex)
            {
                MessageBox.Show("查询数据错误!" + ex.Message);
            }
           
        }
        #endregion


        #region 保存
        private void Dep_confirm_Click_1(object sender, EventArgs e)
        {
            try
            {
                string sql = "update Sounder set 测深仪串口='" + Dep_portName.Text + "',测深仪奇偶校验='" + Dep_parity.Text + "',测深仪波特率='" + Dep_baudRate.Text +
                    "',测深仪停止位='" + Dep_stopBits.Text + "',测深仪数据位='" + Dep_dataBits.Text + "',测深仪握手协议='" + Dep_protocol.Text +
                    "' where 项目名称='" + project + "'";
                DataBaseConnection connection = new DataBaseConnection();
                connection.insertOrUpdate(sql);
              // this.Close();
                this.Hide();
                
            }
            catch (Exception ex)
            {
                MessageBox.Show("数据保存错误!" + ex.Message);
            }
        }
        #endregion


        #region 测试
        private void Dep_test_Click_1(object sender, EventArgs e)
        {
            try
             {
            string portname = Dep_portName.Text.ToString();

            this.port1.PortName = portname;

            //SerialPort port1 = new SerialPort(portname);//取Dep_portName的数据,对你的port1 注册一个事件委托 
            port1.BaudRate = Convert.ToInt32(Dep_baudRate.Text);
            if (Dep_parity.Equals("无"))
            {
                port1.Parity = Parity.None;
            }
            else if (Dep_parity.Equals("奇"))
            {
                port1.Parity = Parity.Odd;
            } if (Dep_parity.Equals("偶"))
            {
                port1.Parity = Parity.Even;
            }
            if(Dep_stopBits.Equals("1"))
            {
                port1.StopBits = StopBits.One;
            }
            else if (Dep_stopBits.Equals("1.5"))
            {
                port1.StopBits = StopBits.OnePointFive;
            }
            else if (Dep_stopBits.Equals("2"))
            {
                port1.StopBits = StopBits.Two;
            }

            port1.DataBits = Convert.ToInt32(Dep_dataBits.Text);
            port1.Handshake = Handshake.None;//////////握手协议有问题未解决---haokl
            port1.RtsEnable = true;//是否请求发送RTS信号,,,有问题未解决---haokl

            port1.DataReceived += new SerialDataReceivedEventHandler(DataReceivedHandler);//绑定事件 

            port1.Open();
           // Thread.CurrentThread.IsBackground = true;//将线程设为后台
           

            //port1.ReadLine();// 向串口接受数据---wenti
            port1.WriteLine("111");//向串口发送数据
            MessageBox.Show("接收测深仪数据成功!");
            
            //port1.Close();                       
                 
             }
             catch (Exception)
             {
                 MessageBox.Show("连接测深仪失败!");
             }
             

        }
        #endregion
        #region 接收数据
        private static void DataReceivedHandler(object sender, SerialDataReceivedEventArgs e)
        {
            
                SerialPort sp = (SerialPort)sender;
                string indata = sp.ReadExisting();// 向串口接受数据
                Console.WriteLine("Data Received:");//输出获取的数据
                Console.Write(indata);
                        
            
        }
        #endregion


        #region 取消
        private void Dep_cancel_Click_1(object sender, EventArgs e)
        {
            this.Close();
        }
        #endregion

    }
}

 但是当一个硬件测试连接成功之后,点保存关闭时,会报 ObjectDisposedException错误。

经过查找总结原因,发现是因为点保存按钮时线程也关闭了,但数据没发送完或者是接收完。

我连接的仪器不想关闭,想一直接收数据,就要实现,form关闭,但线程还在继续。。。

解决办法:

      在form的父窗体声明一个串口,给子窗体,子窗体关闭时,只关闭子窗体的线程,但父窗体的线程还在继续。

      父窗体的代码如下:

      

public SerialPort port1 = new SerialPort();//串口



#region 设置测深仪
        private void 测深仪选项ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            port1.DataReceived += new SerialDataReceivedEventHandler(DataReceivedHandler);//绑定事件 
            string project = CurrentProjectLab.Text;

            Sounder depth = new Sounder(project, isConn, port1);
            depth.Owner = this;
            depth.ShowDialog();
        }
        #endregion
        #region   获取测深仪串口获得的数据
        private static void DataReceivedHandler(object sender, SerialDataReceivedEventArgs e)
        {

            SerialPort sp = (SerialPort)sender;
            string indata = sp.ReadExisting();// 向串口接受数据
            Console.WriteLine("Data Received:");//输出获取的数据
            Console.Write(indata);


        }

  这样就可以啦,,,啊哈哈哈哈哈哈。。。。。。。。。

     当然。。这不是我自己解决的。这是大神给我解决的。。。

    继续向大神学习!

posted @ 2015-10-22 17:23  JaneAi  阅读(628)  评论(0编辑  收藏  举报