Re: .InvokeRequired always resulting in true
- From: Barry Kelly <barry.j.kelly@xxxxxxxxx>
- Date: Tue, 01 Aug 2006 22:21:09 +0100
RobKinney1 <RobKinney1@xxxxxxxxxxxxxxxxxxxxxxxxx> wrote:
Here is my confession though... I have 3 seperate browsers in my program.
I presume they are in different windows? With the error below, are your
windows created on different threads? Do you mean to do this?
Contained within ResetAllDataFields(), I destroy and then recreate all of
them (along with resetting a lot of different data). I simply latched onto
myWebBrowser because it was contained withing ResetAllDataFields() and it was
originally the one throwing a COM error when I was calling this from a worker
thread.
I presume you know that you need to do all this work on your GUI thread,
since Windows' windows have thread affinity.
It seemed that in my function, if I just checked this object beforehand, I
would know if ResetAllDataFields needed to be invoked on the main thread..
But technically since I am grabbing all 3 browsers and destroying/creating
them within this function, I could have used any of them right there.
You should create them on the GUI thread, not in your worker thread,
IMO.
Is this sloppy? If so, how can I tell within a function like
ResetAllDataFieldsSafely() whether or not it is being run from a worker
thread or the main thread (without using a random control)?
In your situation, I'd make sure that everywhere that needs to
communicate with the UI has a reference to something which implements
ISynchronizeInvoke (every control does) and pass a delegate to its
Invoke() method.
Because of the way anonymous delegates capture variables from the outer
context, it's as simple as a 'using' block - Invoke + anonymous delegate
simply and relatively efficiently switches context to the GUI and you
can code on.
I put in your suggested code where my original function call was and it
yielded the following error when it came accross another browser object when
destroying and recreating it:
"Controls created on one thread cannot be parented to a control on a
different thread."
That's a pretty serious error. You need to create and parent controls
all on the GUI thread. There are ways to get separate top-level windows
to run on separate threads in WinForms, but it isn't recommended if it
can be avoided, for complexity reasons.
-- Barry
--
http://barrkel.blogspot.com/
.
- Follow-Ups:
- Re: .InvokeRequired always resulting in true
- From: RobKinney1
- Re: .InvokeRequired always resulting in true
- References:
- Re: .InvokeRequired always resulting in true
- From: Barry Kelly
- Re: .InvokeRequired always resulting in true
- From: RobKinney1
- Re: .InvokeRequired always resulting in true
- Prev by Date: yield and anonymous methods
- Next by Date: Re: Zip Files In C#
- Previous by thread: Re: .InvokeRequired always resulting in true
- Next by thread: Re: .InvokeRequired always resulting in true
- Index(es):
Relevant Pages
|