-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;
}
}
Возможный дубликат [Как обновить GUI из другого потока в C#] (Http://stackoverflow.com/questions/661561/how-to-update-the-gui -из-другой-нить-в-с) –
Посмотрите на класс SerialDataReceivedEventHandler, https://msdn.microsoft.com/en-us/library/system.io.ports.serialport.datareceived(v=vs. 110) .aspx Событие DataReceived создается из объекта SerialPort. Поскольку это событие возникает во вторичном потоке, например в элементах пользовательского интерфейса, может возникнуть исключение потоковой передачи. GUI из отдельной темы. – Bearcat9425