如何从c#中的后台工作进程更新GUI控件? [英] How to update the GUI Controls from Background Worker process in c#?

查看:102
本文介绍了如何从c#中的后台工作进程更新GUI控件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何从c#中的后台工作进程更新GUI控件?

解决方案

您无法从非UI线程调用与UI相关的任何内容。相反,您需要使用 Invoke System.Windows.Threading的方法。 Dispatcher (对于Forms或WPF)或 System.Windows.Forms.Control (仅限表单)。



您将在我过去的答案中找到有关其工作原理和代码示例的详细说明:

Control.Invoke()与Control.BeginInvoke()

使用Treeview扫描仪和MD5的问题



另请参阅有关线程的更多参考资料:

如何在vb.net中的另一个线程上运行keydown事件

在启用禁用+多线程后控制事件未触发



-SA


从后台线程更新UI控件,你需要使用UI的Dispatcher - Window并调用它,如

 _ preShellWindow.Dispatcher.Invoke( System.Windows.Threading.DispatcherPriority.Render, new 操作(()= >  
{
MessageBox.Show( Hii);
}));





您也可以根据您的要求致电更新布局

< pre lang =cs> this .Dispatcher.Invoke(DispatcherPriority.Render,(Action) delegate ( )
{
InvalidateArrange();
InvalidateVisual();
InvalidateMeasure();
UpdateLayout();
});


How to update the GUI Controls from Background Worker process in c#?

解决方案

You cannot call anything related to UI from non-UI thread. Instead, you need to use the method Invoke or BeginInvoke of System.Windows.Threading.Dispatcher (for both Forms or WPF) or System.Windows.Forms.Control (Forms only).

You will find detailed explanation of how it works and code samples in my past answers:
Control.Invoke() vs. Control.BeginInvoke(),
Problem with Treeview Scanner And MD5.

See also more references on threading:
How to get a keydown event to operate on a different thread in vb.net,
Control events not firing after enable disable + multithreading.

—SA


to update UI controls from background thread you need to use the Dispatcher of UI - Window and invoke it like

_preShellWindow.Dispatcher.Invoke(System.Windows.Threading.DispatcherPriority.Render, new Action(() =>
             { 
MessageBox.Show("Hii");
}));



Also you can call Update Layout base on your requirement

this.Dispatcher.Invoke(DispatcherPriority.Render, (Action)delegate()
              {
                  InvalidateArrange();
                  InvalidateVisual();
                  InvalidateMeasure();
                  UpdateLayout();
              });


这篇关于如何从c#中的后台工作进程更新GUI控件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆