从另一个线程刷新控件 [英] Refresh a control from another thread

查看:120
本文介绍了从另一个线程刷新控件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

嗨 我想刷新另一个线程中的控件,我总是收到此异常跨线程操作无效"

解决方案

执行此操作的标准方法是调用UI线程以更新控件.假设您正在使用Windows窗体,则应执行以下操作:

  if (MyControl.InvokeRequired)
{
  MyControl.Invoke( System.Action< string>(MyMethod),myUpdatignValue);
} 

如果您使用的是WPF,则它看起来像这样的

 Application.Current.Dispatcher.Invoke(DispatcherPriority.Normal, Action< string>(MyMethod),myUpdatingValue); 


除了皮特的回答,还有更多详细信息:

您无法从非UI线程调用与UI相关的任何操作.相反,您需要使用System.Windows.Threading.DispatcherInvokeBeginInvoke方法(对于Forms或WPF)或System.Windows.Forms.Control(仅对于Forms).

在我过去的答案中,您将找到有关其工作原理的详细说明和代码示例:
Control.Invoke()与Control.BeginInvoke() [ ^ ],
Treeview扫描仪和MD5的问题 [如何获取keydown事件在vb.net中的不同线程上操作 [启用禁用+多线程后控件事件不会触发 [ ^ ].

—SA


hi i want to do a refresh for a control from another thread, i always getting this exception "Cross-thread operation not valid"

解决方案

The standard way to do this is to Invoke onto the UI thread to update the control. Assuming you are using Windows Forms, you would do something like this:

if (MyControl.InvokeRequired)
{
  MyControl.Invoke(new System.Action<string>(MyMethod), myUpdatignValue);
}

If you are using WPF, it would look like this

Application.Current.Dispatcher.Invoke(DispatcherPriority.Normal, new Action<string>(MyMethod), myUpdatingValue);


In addition to the answer by Pete, some more detail:

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[^].

The call to Control.InvokeRequired may or may not be needed. Basically, it should be called on the control which is inserted to the same UI hierarchy as the control to be used for a call Control.Invoke or Control.BeginInvoke. That is, those controls do not have to be the same. If the calling thread is not the UI thread working with these controls, Control.InvokeRequired always returns true, false otherwise. As invocation methods are usually called from a non-UI thread (always true), the check is usually not required. The Control.InvokeRequired is needed in more rare situations where invocation is called from the method which is itself called sometimes from the correspondent UI thread (when invoke is not required) and sometimes form the some other thread (when invoke is required). In this way, the call to Control.InvokeRequired is needed pretty rarely.

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


这篇关于从另一个线程刷新控件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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