简体   繁体   中英

Should I check InvokeRequired before Invoke()?

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.

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

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).

And here's a quote from that link:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM