"Cross-thread operation not valid" even when .InvokeRequired is false

M

Mesan

I'm getting a "Cross-thread operation not valid" Exception and I can't
figure out why.

I've got a BackgroundWorker that creates a UserControl with a whole lot
of other user controls inside of it, full of data I'm getting from the
database. When my background worker completes I take e.Result and cast
it back into a UserControl. I create a TabPage, add the returned
UserControl to the Controls of the new TabPage and *BAM* there's my
exception.

Just before I add the UserControl to the new TabPage's Controls I've
looked at the InvokeRequired properties for the UserControl, the new
TabPage and even my main form and they're all false, leading me to
believe that I should't expect to see such a cross-thread operation.

What gives?
 
J

Jon Skeet [C# MVP]

Mesan said:
I'm getting a "Cross-thread operation not valid" Exception and I can't
figure out why.

I've got a BackgroundWorker that creates a UserControl with a whole lot
of other user controls inside of it, full of data I'm getting from the
database. When my background worker completes I take e.Result and cast
it back into a UserControl. I create a TabPage, add the returned
UserControl to the Controls of the new TabPage and *BAM* there's my
exception.

Just before I add the UserControl to the new TabPage's Controls I've
looked at the InvokeRequired properties for the UserControl, the new
TabPage and even my main form and they're all false, leading me to
believe that I should't expect to see such a cross-thread operation.

What gives?

Well, you should never have a control in a Window which "belongs" to a
different thread. The control itself "belongs" to the worker thread -
and although it sounds like InvokeRequired called on the UserControl
should really return true, even if you used Invoke you wouldn't solve
the problem as you'd then be in the wrong thread from the form's point
of view.

My *guess* is that the reason InvokeRequired isn't spotting the problem
is that the worker thread isn't running a message pump - but that's
only a guess.

Just create all the controls on your main UI thread, doing the heavy
non-UI-related work on another thread, and you should be fine.
 

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