调用主线程的方法在另一个线程的事件处理程序

编程入门 行业动态 更新时间:2024-10-27 02:22:24
本文介绍了调用主线程的方法在另一个线程的事件处理程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有一个基于另一个对象引发的事件更新另一个GUI。

I have to update another GUI based on events raised by another object.

public void PLCMessage_Received(object sender, PLCMessageEventArgs e) { string tempstr = (String)e.Message; UpdateGUI(tempstr); } public void UpdateGUI(string temp) { if (temp == "A1Y101") { lbll2heartbeatack.Dispatcher.Invoke(System.Windows.Threading.DispatcherPriority.Normal, new Action(delegate() { lbll2heartbeatack.Content = "Ack-OK"; lbll2heartbeatack.Foreground = Brushes.Green; })); } else if (temp == "A1Y102") { lbll2chargeingscheduleack.Dispatcher.Invoke(System.Windows.Threading.DispatcherPriority.Normal, new Action(delegate() { lbll2chargeingscheduleack.Content = "Ack-OK"; lbll2chargeingscheduleack.Foreground = Brushes.Green; })); } else if (temp == "A1Y103") { lbll2productinfo.Dispatcher.Invoke(System.Windows.Threading.DispatcherPriority.Normal, new Action(delegate() { lbll2productinfo.Content = "Ack-OK"; lbll2productinfo.Foreground = Brushes.Green; })); } else if (temp == "A1Y104") { lbll2entrytrackingack.Dispatcher.Invoke(System.Windows.Threading.DispatcherPriority.Normal, new Action(delegate() { lbll2entrytrackingack.Content = "Ack-OK"; lbll2entrytrackingack.Foreground = Brushes.Green; })); } else if (temp == "A1Y105") { lbll2exittrackinginfoack.Dispatcher.Invoke(System.Windows.Threading.DispatcherPriority.Normal, new Action(delegate() { lbll2exittrackinginfoack.Content = "Ack-OK"; lbll2exittrackinginfoack.Foreground = Brushes.Green; })); } else if (temp == "A1Y106") { lbll2rejectreqack.Dispatcher.Invoke(System.Windows.Threading.DispatcherPriority.Normal, new Action(delegate() { lbll2rejectreqack.Content = "Ack-OK"; lbll2rejectreqack.Foreground = Brushes.Green; })); } }

有更多的GUI控件的数目,我有更新。对于每一个控制我写个Invoke方法。是否有可能在主界面调用,这样我可以通过自己的名义直接GUI控件结果?注:我的应用程序的开发是在Visual Studio 2010

There are more number of GUI controls which I have to update. For every control I writing th Invoke method. Is it possible to call on main GUI so that i can GUI controls directly by their name? Note: My application development is in Visual Studio 2010

推荐答案

您可以使用的的SynchronizationContext 为此目的,使生活更轻松。

You can use SynchronizationContext for that purpose, that makes life easier.

private SynchronizationContext uiContext = SynchronizationContext.Current; public void PLCMessage_Received(object sender, PLCMessageEventArgs e) { string tempstr = (String)e.Message; uiContext.Send((x)=> UpdateGUI(tempstr), null);//For synchronous //Or uiContext.Post((x)=> UpdateGUI(tempstr), null);//For Asynchronous }

奖金念叨的的SynchronizationContext

更多推荐

调用主线程的方法在另一个线程的事件处理程序

本文发布于:2023-11-09 15:04:57,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1572681.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:线程   主线   事件   程序   方法

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!