我正在开发一个使用外部设备使用USB协议与电子板通信的应用程序。当我想显示在TextBlock内部通信期间获得的结果时,会出现错误消息
调用线程无法访问此对象,因为另一个线程拥有它
如何停止此帖子或在我的文本块中打印相应的信息?
这里使用的代码:
/// ******************************************************************
/// <summary>
/// RX_Thread
///
/// Description:
/// Second thread which receives data from configured receive port
/// (CANDemo_RxChannel)of XL interface.
/// </summary>
/// ******************************************************************
#region EVENT THREAD (RX)
public void RX_Thread()
{
// object to be fill with received data
XLClass.xl_event receivedEvent = new XLClass.xl_event();
// result of XL driver func. calls
XLClass.XLstatus xlStatus = XLClass.XLstatus.XL_SUCCESS;
// WaitForSingleObject values
WaitResults waitResult = new WaitResults();
// note: this thread is destroyed by MAIN
while (true)
{
// wait for hardware events
waitResult = (WaitResults)WaitForSingleObject(CANDemo_RxChannel.eventHandle, 1000);
// if event occured...
if (waitResult != WaitResults.WAIT_TIMEOUT)
{
// ...init xlStatus first
xlStatus = XLClass.XLstatus.XL_SUCCESS;
// afterwards: while hw queue is not empty...
while (xlStatus != XLClass.XLstatus.XL_ERR_QUEUE_IS_EMPTY)
{
// ...receivedata from hardware queue
xlStatus = CANDemo_RxChannel.xlReceive(ref receivedEvent);
// if receiveing succeed...
if (xlStatus == XLClass.XLstatus.XL_SUCCESS)
{
// ...print rx data
string BigContained = CANDemo.XL_GetEventString(receivedEvent);
//GetInfo(BigContained);
// ((XLClass.xl_event)xlEventCollection.xlEvent[0]).tagData.can_Msg.id = 0x74D;
if (receivedEvent.tagData.can_Msg.id == 0x76D)
{
if (receivedEvent.tagData.can_Msg.data[0] == Convert.ToByte(2) && receivedEvent.tagData.can_Msg.data[1] == Convert.ToByte(80) && receivedEvent.tagData.can_Msg.data[2] == Convert.ToByte(250))
{
// i want to writ the data in my Texbloxk but i get error :
txtframeContainer.Text = "Enter in diagnostic mode SupplierSpecific --> Ok ";
}
}
}
}
}
// no event occured
}
}
#endregion
/// ------------------------------------------------------------------
等待你的反馈......
答案 0 :(得分:1)
你只能从你的ui线程更新ui,所以如果你更新一个ui对象,你必须获得ui线程并在该线程上调用更新:
if (Application.Current.Dispatcher.CheckAccess())
{
txtframeContainer.Text = Result;
}
else
{
Application.Current.Dispatcher.Invoke((Action)(() =>
{
txtframeContainer.Text = "Enter in diagnostic mode SupplierSpecific --> Ok ";
}));
}
答案 1 :(得分:0)
尝试在不是UI线程的线程上更新UI控件时会导致此错误。
看看这个问题:How to update the GUI from another thread in C#?它应该给你答案