Threading issue -- InvokeRequired on Form is unreliable.

S

Sgt. Sausage

Problem. Work-around. No issues, just looking to see
if I'm the only one that's seen this.

I just lost 3 hours (shoulda found it sooner) to the
InvokeRequired on a form being somewhat unreliable. It
will sometimes return incorrect results.

I've got it isolated to the Form's Handle property. If
nothing touches my form's Handle before the supplementary
threads are fired off, then InvokeRequired has about a
50/50 shot of being correct.

The minute something touches the Form's Handle property,
it becomes 100% reliable.

I'm guessing (relatively new to multi-threading: 1st day
at it today <grin>) that maybe there's some kind of delay
on a WinForm that a handle doesn't get created right away,
as soon as the Form is instantiated. My guess is that the
Handle is somehow delayed, and under certain circumstances,
that causes the handle to be created under one of my
supplementary (non-UI) threads. I'm also guessing that
InvokeRequired uses the handle to get back to the actual
Thread (somehow). So, it appears to me (by some serious
guessing) that if I don't touch the Handle in any way
before my Thread kicks off, but somewhere in my thread,
the Handle is first touched (and first created), then
the Handle is created on my Thread, rather than on the
UI thread.

This is a whole bunch-o-pulled out my arse wild guessing,
but it makes sense to me.

If I do anything that touches the Handle first, before
I fire my Thread(s) off, then everything works AOK and
InvokeRequired works as advertised. If I don't touch
the Handle, it goes all squirrely.

Can anyone duplicate or confirm this. Am I off base
here?

For now, the first thing I do on the Form is set a
useless variable to the Handle, so that something has
touched it and it gets created. It's solved the problem,
but I'm not sure if the above is out in left field or
if I'm on the right track on why it's happening.

I've looked at MS and couldn't find anything.
 
C

cryolitte

Just had similar problems with InvokeRequired. Debug lines indicate
that it was returning false when the code was invoked by my worker
threads, until a later point when it starts returning the right value
again.

Have you tried the form's CreateHandle() method? It seems to work for
me in ensuring that InvokeRequired returns the correct value.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top