Mesan <93*****@gmail.com> wrote:
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.
--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet Blog:
http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too