Recommended Posts

"Cross-thread operation not valid: Control 'textBox' accessed from a thread other than the thread it was created on."
I need to access that control when the thread is complete; is there a way to tell when a thread is completed other than specifically checking it (there is no main loop)?

0

Share this post

Link to post

Share on other sites

Look at Control.Invoke and/or Control.BeginInvoke. It will execute a delegate on the thread that the control was created. With anon delegates in 2.0 you can even put the code inline so no need to make another function and all that jazz

Share this post

Link to post

Share on other sites

I get the feeling that you were ironic saying "Thank you .NET 2.0" ;-)

But you really should thank 2.0. I've seen lots of people on the web complaining that 2.0 broke their application with the cross-thread exception. But 2.0 didn't *broke* your application. It *informs* you that your application *was broken* on the first place.

Even in .NET 1.1 the documentation states that cross-thread calls are to be avoided. But many programmers didn't know/didn't care. Now .NET 2.0 throw on these cases to enforce correct programming.

Cross-thread calls on GUI controls can create deadlocks, even if they really don't look bad. Reason for this lies in the Win32 infrastructure, and I'll let you google it if you're curious.

As joelmartinez wrote, the way to call a method on a Control class from another thread is to call Invoke or BeginInvoke on it. FYI, there are two other methods you can call safely from any thread: EndInvoke and CreateGraphics.

Your post had another question in it:

Quote:

is there a way to tell when a thread is completed other than specifically checking it (there is no main loop)?

Answer: This is exactly what the Thread::Join method does. It blocks the calling thread until the thread has finished. There are overloads if you want a timeout.

Share this post

Link to post

Share on other sites

Yeah, I love Backgroundworker. I want to add my Thank you .NET 2.0 by myself. I've started directly with it, and had to realize later, that i most the time use the 2.0 only features. I'd be terribly lost in a pre 2.0 environment :D

and thanks to inform about Control.Invoke. something new i have to check out :D

0

Share this post

Link to post

Share on other sites

Original post by Daniel MillerBy the way, what do you mean when you say the deadlocks don't look bad?

I probably didn't express myself very well. What I wanted to say is that you can create deadlock with calls that really look inoffensive. E.g. just getting a Text property from a control can potentially create a deadlock if you're not doing it from the right thread.