我正在尝试将数据从串行写入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());
}
}
}
答案 0 :(得分:1)
试试这个..
private void AppendText(string text)
{
Application.Current.Dispatcher.Invoke((Action)(() =>
{
_window.Dev_output.Text += string.Format("{0}{1}", text, Environment.NewLine);
}));
}
答案 1 :(得分:1)
在你的serialport类中,你需要存储UI线程的调度程序,它在构造函数中很方便。因此,将其存储起来,然后每次附加文本时都需要在该调度程序上调用
class SerialPortProgram
{
// Create the serial port
private SerialPort port;
MainWindow _window;
private Dispatcher _dispatcher;
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 += port_DataReceived;
_dispatcher = Dispatcher.CurrentDispatcher;
// Begin communications
port.Open();
}
private void AppendText(string text)
{
_dispatcher.Invoke(() => {
_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());
}
}