调用Invoke有什么问题,不管InvokeRequired? [英] What's wrong with calling Invoke, regardless of InvokeRequired?

查看:149
本文介绍了调用Invoke有什么问题,不管InvokeRequired?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经看到了跨线程访问GUI控件的常见设置,如下所述:
将线程安全访问方法写入Windows窗体控件的最短方法

I've seen the common setup for cross threading access to a GUI control, such as discussed here: Shortest way to write a thread-safe access method to a windows forms control

我发现的所有网页点击都会描述类似的东西。

All the web hits I found describe a similar thing.

然而,为什么我们需要检查InvokeRequired?我们不能直接调用Invoke?

However, why do we need to check InvokeRequired? Can't we just call Invoke directly?

我假设答案是否定的,所以我真正的问题是为什么?

I assume the answer is no, so my real question is 'why'?

推荐答案

从非UI线程我们不能触摸UI - 非常糟糕的事情可能发生,因为控件具有线程关联性。所以从非UI线程我们必须(最小)调用调用 BeginInvoke

From non-UI threads we can't touch the UI - very bad things can happen, since controls have thread affinity. So from a non-UI thread we must (at a minumum) call Invoke or BeginInvoke.

然而,对于UI线程,我们不要要调用调用很多时间;问题是,如果您的UI线程已经被 ,那么它仍然有不必要的开销,向窗体的泵发送消息并处理它。

For UI-threads, however - we don't want to call Invoke lots of time; the issue is that if you are already on the UI thread, it still has the unnecessary overhead of sending a message to the form's pump and processing it.

实际上,在大多数线程代码中,你知道你希望在 -UI线程上调用一个特定的方法,所以在这种情况下,没有额外的开销:只需调用调用

In reality, in most threading code you know you expect a specific method to be called on a non-UI thread, so in those cases, there is no additional overhead: just call Invoke.

这篇关于调用Invoke有什么问题,不管InvokeRequired?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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