SerialPort(SerialDataReceivedEventArgs)System.InvalidOperationException

时间:2016-09-12 13:07:15

标签: c# multithreading exception serial-port

  

抛出异常:'System.InvalidOperationException'   WindowsBase.dll中                附加信息:                Impossibile accedere all'oggetto dal thread chiamante                perchétaleoggettoèdiproprietàdiun altro thread。

public partial class MainWindow : Window
{
    int baudRate { get; }
    Parity parity { get; }
    int dataBits { get; }
    StopBits stopBits { get; }
    Handshake handshake { get; }
    string portName { get; }
    MainWindow mainWindow;
    SerialPort _serialPort { get; set; }

    public MainWindow()
    {
        InitializeComponent();
        //var conf = new ConfigScanner(this);
        var conf_file_path = string.Format("{0}scannerCOMconf.ini", AppDomain.CurrentDomain.BaseDirectory);
        if (!File.Exists(conf_file_path)) return;
        string[] fileConf = File.ReadAllLines(conf_file_path);
        portName = fileConf[0];
        baudRate = Convert.ToInt32(fileConf[1]);
        parity = (Parity)Enum.Parse(typeof(Parity), fileConf[2]);
        dataBits = Convert.ToInt32(fileConf[3]);
        stopBits = (StopBits)Enum.Parse(typeof(StopBits), fileConf[4]);
        handshake = (Handshake)Enum.Parse(typeof(Handshake), fileConf[5]);
        Open();
    }


    public bool Open()
    {
        _serialPort = new SerialPort();
        try
        {
            _serialPort.BaudRate = baudRate;
            _serialPort.DataBits = dataBits;
            _serialPort.Handshake = handshake;
            _serialPort.Parity = parity;
            _serialPort.PortName = portName;
            _serialPort.StopBits = stopBits;
            _serialPort.DataReceived += new SerialDataReceivedEventHandler(scanBarcode);
            _serialPort.Open();
        }
        catch (Exception e)
        {
            Console.WriteLine(e.Message);
            return false;
        }
        return true;
    }

    void scanBarcode(object sender, SerialDataReceivedEventArgs e)
    {
        SerialPort sp = (SerialPort)sender;
        string indata = sp.ReadExisting();            
        Console.Write(indata);
        /*
         Exception thrown: 'System.InvalidOperationException' in WindowsBase.dll
         Additional information: 
         Impossibile accedere all'oggetto dal thread chiamante 
         perché tale oggetto è di proprietà di un altro thread.*/
        textbox1.Text = indata;
    }
}

1 个答案:

答案 0 :(得分:0)

您可以使用委托在正确的线程中调用GUI内容。我会做类似的事情:

void scanBarcode(object sender, SerialDataReceivedEventArgs e)
{
    string indata = _serialPort.ReadExisting();            

    this.Invoke((MethodInvoker)delegate
    {
        textbox1.Text = indata;
    }
}