Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How expensive is the IsInvokeRequired

Is there any documentation on exactly how expensive it is:

if (x.IsInvokeRequired)
{
    beginInvoke . . . .
}
  • If you have a case where 90% of the time is on a background thread (and thus required) is it worth it?
  • If you have a case where 90% of the time is on a UI thread (and thus not required) is it worth it?

Any metrics around this would be great.

like image 930
leora Avatar asked Mar 22 '26 08:03

leora


1 Answers

Real Answer:

Use a profiler

Fuzzy Answer:

I think you need to consider the relative costs of both functions vs. the absolute cost of InvokeRequired.

InvokeRequired for Control essentially compares the current ThreadId with the expected ThreadId. If you look in reflector the code is slightly more complex but in effect that's what it's doing. This is fairly cheap as it's just a few function calls and a comparison.

BeginInvoke involves taking several locks, adding delegates to an invoke queue and potentially a Marshal between threads. This code is much more expensive relative to the actual InvokeRequired call (likely an order of magnitude or 2). You would need a great deal more calls where InvokeRequired returns true before you would see any gain by just going straight to BeignInvoke.

like image 169
JaredPar Avatar answered Mar 23 '26 21:03

JaredPar