首页 > 解决方案 > 以安全的方式使用 C# WPF 关闭 SerialPort 对象

问题描述

我在我的程序中使用 RS-232 条形码,它让我进入一个新窗口新窗口也应该能够自行关闭并再次打开第一个窗口并让我使用另一个条形码

我的代码停留在下一行:barcodeManager.Dispose();我做错了什么?

我将展示我的代码的重要部分:如果您需要我的代码的更多部分,请告诉我添加

我的主要模型如下所示:

我的主窗口循环:

public FirstWindowMV(Action close)
{
    keepLoop = true;
    this.close = close;
    TblTray_StepInSequence = null;
    tblTray = null;

    do
    {
        if(GetBarcodeData() == false)
        {
            return;
        }

        if (tblTray != null && TblTray_StepInSequence != null)
        {
            if(OpenMainWindow() == false)
            {
                return;
            }
        }
    } while (keepLoop);
}

这部分代码:OpenMainWindow()做一些逻辑

条码获取方法:

 private bool GetBarcodeData()
        {
            BarcodeSearcher barcodeSearcher = new BarcodeSearcher();
            barcodeSearcher.ShowDialog();
            BarcodeSearcherMV bmv = (BarcodeSearcherMV)barcodeSearcher.DataContext;

            if (bmv.ExitResultDialog == true)
            {
                close();
                keepLoop = false;
            } 
            TblTray_StepInSequence = bmv.TblTray_StepInSequence;
            tblTray = bmv.tblTray;
            Barcode = bmv.Barcode;

            return keepLoop;
        }

我的 BarcodeSearcherMV 看起来像:

public class BarcodeSearcherMV : INotifyPropertyChanged
    {
        public bool ExitResultDialog;
        public string BarcodeData { get; set; }

        private BarcodeManager barcodeManager;

        private ICommand _Exit;

        public ICommand Exit
        {
            get
            {
                if (_Exit == null)
                {
                    _Exit = new RelayCommand((param) => ExitAction());
                }
                return _Exit;
            }
        }

        private void ExitAction()
        {
            ExitResultDialog = true;
            close();
        }

        public BarcodeSearcherMV()
        {
        }

        public BarcodeSearcherMV(Action close)
        {
            this.close = close;
            barcodeManager = new BarcodeManager(barcodeAction);
        }

        private string barcode;
        private Action close;

        public string Barcode
        {
            get
            {
                return barcode;
            }
            set
            {
                barcode = value;
                barcodeAction(barcode);
            }
        }

        public tblTray_StepInSequence TblTray_StepInSequence;
        public tblTray tblTray;

        private void barcodeAction(string barcode)
        {
            TblTray_StepInSequence = DigatronSQL12ManagerInstance.GetTblTray_StepInSequences(barcode);
            tblTray = DigatronSQL12ManagerInstance.GetTblTray(barcode);
          
            if (TblTray_StepInSequence != null && tblTray  != null)
            {
                this.barcode = barcode;
                barcodeManager.Dispose();
                Application.Current.Dispatcher.Invoke(new Action(() => {
                    close();
                }));
            }
        }

        public event PropertyChangedEventHandler PropertyChanged;
    }

我的 BarcodeManager 类:

   public class BarcodeManager:IDisposable
    {
        private Action<string> barcodeAction;
        //public List<SerialPort> ScanCodeSerialPort { get; set; }
        public SerialPort ScanCodeSerialPort { get; set; }

        public BarcodeManager(Action<string> _barcodeAction)
        {
            barcodeAction = _barcodeAction;
            try
            {
                string[] ports = SerialPort.GetPortNames();

                SerialPortIniManager SerialPortIniManager = new SerialPortIniManager();
                string portName = SerialPortIniManager.GetCurrentPortName();

                try
                {
                    SerialPortIniManager spim = new SerialPortIniManager();
                    ScanCodeSerialPort = new SerialPort(portName, Convert.ToInt32(spim.GetBaudRate()),
                        (Parity)Enum.Parse(typeof(Parity), spim.GetParity()), Convert.ToInt32(spim.GetDataBits()),
                        (StopBits)Enum.Parse(typeof(StopBits), spim.GetStopBits()));
                    ScanCodeSerialPort.DataReceived += DataRecive;
                    ScanCodeSerialPort.Open();
                }
                catch (Exception ex)
                {
                    LocalPulserDBManagerInstance.WriteLog(ex.StackTrace, ex.Message);
                }
            }
            catch (Exception ex)
            {
                LocalPulserDBManagerInstance.WriteLog(ex.StackTrace, ex.Message);
                ScanCodeSerialPort = null;
            }
        }
        private void DataRecive(object serialPort, SerialDataReceivedEventArgs _event) { 
            Application.Current.Dispatcher.Invoke(new Action(() => {
            barcodeAction(((SerialPort)serialPort).ReadExisting().Trim()); 
            }));
        }
        
        public void Dispose()
        {
            
            try
            {
                if (ScanCodeSerialPort.IsOpen)
                {
                    ScanCodeSerialPort.DataReceived -= DataRecive;
                    Application.Current.Dispatcher.Invoke(() =>
                    {
                        ScanCodeSerialPort.Close();
                    });
                }
            }
            catch (Exception ex)
            {
                LocalPulserDBManagerInstance.WriteLog(ex.StackTrace, ex.Message);
                throw ex;
            }

        }
    }

我的 SerialPortIniManager 对象:

public class SerialPortIniManager : IniBase
    {
        private static readonly string iniPath = @"C:\pulser\GlobalConfig.ini";
        public SerialPortIniManager() : base(iniPath)
        { }

        public string GetBaudRate()
        {
            try
            {
                return GetString("SerialPort", "BaudRate", "9600");
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        public string GetParity()
        {
            try
            {
                return GetString("SerialPort", "Parity", "None");
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        public string GetDataBits()
        {
            try
            {
                return GetString("SerialPort", "DataBits", "7");
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        public string GetStopBits()
        {
            try
            {
                return GetString("SerialPort", "StopBits", "One");
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        public string GetCurrentPortName()
        {
            try
            {
                return GetString("SerialPort", "CurrentPortName", "COM1");
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
    }

我的 ini 文件:C:\pulser\GlobalConfig.ini

[SerialPort]
BaudRate = 9600
Parity = None
DataBits = 7
StopBits = One
CurrentPortName = COM1

Call Stuck 卡点图片

在此处输入图像描述

标签: c#wpfserial-portbarcodedispose

解决方案


推荐阅读