【发布时间】:2016-06-02 20:36:31
【问题描述】:
我正在开发一个应用程序,它使用连接到我计算机的端口 com 的 GPS。
我的应用程序有 2 个窗口,第一个是显示窗口,我将显示我所有的 GPS 数据,第二个是地图。
我已经把我所有的打开 COM 端口的代码放在 App.cs 中阅读了
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Threading;
using tmagpsapi;
namespace TDF
{
public partial class App : Application
{
private tmagpsapi.NMEA gps;
private tmaSerialport sp;
private void Application_Startup(object sender, StartupEventArgs e)
{
gps = new NMEA();
sp = new tmaSerialport();
sp.ComPortOpen += new tmaSerialport.ComPortOpenEventHandler(comportOpen);
sp.ComPortError += new tmaSerialport.ComPortErrorEventHandler(comportError);
sp.ComPortClosed += new tmaSerialport.ComPortClosedEventHandler(comportClosed);
gps.SuccessfulFix += new NMEA.SuccessfulFixEventHandler(gpsSuccessFix);
sp.Openport(30, System.IO.Ports.Parity.None, tmagpsapi.tmaSerialport.enumDatabits.Bit8, System.IO.Ports.StopBits.One, tmagpsapi.tmaSerialport.enumBaudRates.BaudRate9600);
sp.LineRecieved += sp_LineRecieved;
}
void sp_LineRecieved(string Data)
{
try
{
if (this.MainWindow != null)
{
var currentWindow = this.MainWindow as GPSWindow;
currentWindow.GPSHandle(Data);
}
else
{
System.Windows.Forms.MessageBox.Show("NULL");
}
}
catch (Exception e)
{
Console.WriteLine(e.Message);
System.Windows.Forms.MessageBox.Show(e.Message);
}
}
private void comportClosed()
{
Console.WriteLine("COM PORT CLOSED");
System.Windows.Forms.MessageBox.Show("COM PORT CLOSED");
}
private void comportError(System.Exception es, String message)
{
Console.WriteLine("Error : " + message);
System.Windows.Forms.MessageBox.Show("Error : " + message);
}
private void comportOpen() {
Console.WriteLine("COM PORT OPENED");
System.Windows.Forms.MessageBox.Show("COM PORT OPENED");
}
private void gpsSuccessFix(tmagpsapi.NMEA_Position position)
{
Console.WriteLine("GPS OK");
System.Windows.Forms.MessageBox.Show("GPS OK");
}
private void Application_Exit(object sender, ExitEventArgs e)
{
sp.Close();
}
}}
正如您在这段代码中看到的,当我启动应用程序时,我打开了我的 COM 端口,当我关闭应用程序时,我关闭了它。
当我的 COM 端口上有新数据时,会调用函数 sp_LineRecieved。 在这个函数中,我想将这些数据发送到我打开的 currentWindow 中。为此,我创建了一个名为“GPSWindow”的界面(使用一种方法 void GPSHandle(string data))
但是当我尝试调用 currentWindow.GPSHandle(Data) 时,我的 catch 中出现错误:“调用线程无法访问此对象,因为不同的线程拥有它”。
我曾尝试使用 Application.Current.Dispatcher,但我尝试的每一件事都会向我发送此结果。
也许我可以使用事件处理程序传递这些数据,但我不知道该怎么做。
我的问题是:
如何访问已被其他线程使用的线程?
void GPSWindow.GPSHandle(string data)
{
System.Windows.Forms.MessageBox.Show("GPS : " + data);
}
【问题讨论】:
-
具体发生在哪一步异常?你如何操作
GPSHandle中的 UI 元素?能否提供异常堆栈跟踪? -
currentWindow.GPSHandle(Data) 上附加的异常,我把函数的代码放在消息里
-
如果你真的不想在 app.cs 中做,试试this solution
标签: c# wpf multithreading gps