2016-09-12 75 views
-2

拋出異常:「System.InvalidOperationException」在 WindowsBase.dll中 附加信息: 因爲該目的是由另一個線程性質所屬不能從調用線程 訪問該對象。的SerialPort(SerialDataReceivedEventArgs)System.InvalidOperationException

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; 
    } 
} 
+0

的可能的複製[?如何更新從C#另一個線程的GUI(Http://stackoverflow.com/questions/661561/how-to-update-the-gui - 從-另一個線程在-C) –

+0

看看在SerialDataReceivedEventHandler類,https://msdn.microsoft.com/en-us/library/system.io.ports.serialport.datareceived(v=vs。 110)的.aspx DataReceived該事件當從對象的SerialPort接收到的數據上的副螺紋凸起。由於引發此事件在輔助線程,而不是主線程,嘗試修改在主線程中的一些元素,比如UI元素,可以提高一個線程異常。你需要參考上面的評論如何從單獨的線程中更新GUI。 – Bearcat9425

回答

0

您可以使用委託調用圖形化的東西,在正確的線程。我會做這樣的事情:

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

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