我应该在Invoke()之前检查InvokeRequired吗? [英] Should I check InvokeRequired before Invoke()?

查看:135
本文介绍了我应该在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吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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