我正在尝试将数据从串行写入USB
设备到文本字段,但它一直在抛出:
调用线程无法访问此对象,因为不同的线程拥有它
我知道我必须通过调度或类似的方式做一些事情,但不确定我们从哪里开始。我确信这很简单,但我正在画一个空白。这是我的代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.IO.Ports;
using System.Windows.Threading;
namespace serial_app_one
{
public partial class MainWindow : Window
{
private SerialPortProgram _serial;
public MainWindow()
{
InitializeComponent();
_serial = new SerialPortProgram(this);
}
}
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
class SerialPortProgram
{
// Create the serial port
private SerialPort port;
MainWindow _window;
public SerialPortProgram(MainWindow window)
{
_window = window;
AppendText("Incoming Data:");
port = new SerialPort("COM3", 9600, Parity.None, 8, StopBits.One);
// Attach a method to be called when there
// is data waiting in the port's buffer
port.DataReceived += new
SerialDataReceivedEventHandler(port_DataReceived);
// Begin communications
port.Open();
}
private void AppendText(string text)
{
_window.Dev_output.Text += string.Format("{0}{1}", text, Environment.NewLine);
}
private void port_DataReceived(object sender,
SerialDataReceivedEventArgs e)
{
// Show all the incoming data in the port's buffer
AppendText(port.ReadExisting());
}
}
}