我应该在Invoke()之前检查InvokeRequired吗?

编程入门 行业动态 更新时间:2024-10-25 02:28:41
本文介绍了我应该在Invoke()之前检查InvokeRequired吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

在编写将要从应用程序的不同部分使用的代码时,有时我的代码可能会在UI线程上执行,也可能不会.我想避免从另一个线程(已经在主线程上)在主线程上调用的开销.简单的方法是检查 InvokeRequired 首先.但这真的需要吗?我希望系统避免调用本身.

When writing code that will be consumed from different parts of my application, I sometimes have code that might be executed on the UI thread, or might not. I would like to avoid the overhead of Invoking on the main thread from another thread, what is already on the main thread. The simple way is to check InvokeRequired first. But is that really needed? I would expect the system to avoid the overhead by itself from within Invoke itself.

我可以直接调用Invoke吗,系统会在不需要时避免调用"吗?

Is that true that I can just call Invoke and the system will avoid "Invoking" if not needed?

推荐答案

根据在评论中使用Hans Passant 调用 的代码足够智能,以至于在主线程上执行时不会调用".请参见源代码 (由Hans提供的链接).

According to Hans Passant in a comment the code for Invoke is intelligent enough to not "invoke" when being executed on the main thread. See source code (link supplied by Hans).

这是该链接的引文:

如果我们在同一线程上,我们不想等待,否则我们会 僵局.

We don't want to wait if we're on the same thread, or else we'll deadlock.

更多推荐

我应该在Invoke()之前检查InvokeRequired吗?

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

发布评论

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

>www.elefans.com

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