What#39;s wrong with calling Invoke, regardless of InvokeRequired?(不管 InvokeRequired 调用 Invoke 有什么问题?)
问题描述
我已经看到了对 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 线程调用 Invoke 或 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 线程 - 我们不想要调用 Invoke 很多时间;问题是,如果您已经在 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 线程上调用特定方法,因此在这些情况下,不需要额外的开销:只需调用 Invoke.
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.
这篇关于不管 InvokeRequired 调用 Invoke 有什么问题?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:不管 InvokeRequired 调用 Invoke 有什么问题?
基础教程推荐
- 在 VB6 或经典 ASP 中使用 .NET 2022-01-01
- 从 C# 控制相机设备 2022-01-01
- C# 9 新特性——record的相关总结 2023-04-03
- SonarQube C# 分析失败“不是指针的有效行偏移" 2022-01-01
- 获取C#保存对话框的文件路径 2022-01-01
- 如果条件可以为空 2022-01-01
- 重新排序 WPF TabControl 中的选项卡 2022-01-01
- Mono https webrequest 失败并显示“身份验证或解密失败" 2022-01-01
- 将数据集转换为列表 2022-01-01
- 更新 Visual Studio 中的 DataSet 结构以匹配新的 SQL 数据库结构 2022-01-01
