Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Impossible (how I hate to use this word) cross threading error?

Can anybody please explain how this could possibly happen?

I am completely aware of programming with thread safety in mind and as you can see I am catering for UI updates via a form InvokeRequired check here, everything has been working fine and no changes to break this that I am aware, and now suddenly just as I'm programming other parts of the application (perhaps added to this method at one stage? I just can't remember) I intimitently, receive this error:

alt text

Firstly, if InvokeRequired = true, that should mean BeginInvoke() executed, the method is [queued] to be re-called and InvokeRequired should equal false?

I should not receive this exception as it should be catered for?

Hope to hear from some multi threading guru's :)

Graham

like image 673
GONeale Avatar asked Feb 09 '09 05:02

GONeale


1 Answers

I suspect InvokedRevoked might be lying to you. A WinForm Control defers creation of the Control's underlying Win32 HWND until a method call actually needs it. InvokeRequired will return false if the HWND has not been created yet.

For a detailed explanation, see: "Mysterious Hang or The Great Deception of InvokeRequired"

If your background thread queries InvokeRequired before the UI thread has caused the Control to lazily create its HWND, InvokeRequired will (incorrectly) tell your background thread that it does not need to use Invoke() to pass control back to the UI thread. When the background thread then accesses the Control, BAM! "InvalidOperationException: Cross-thread operation not valid!"

The UI thread can manually force the Control to create its HWND handle to so Control.InvokeRequired will know the UI thread is the Control's owner:

Control control = new Control();
IntPtr handle = control.Handle; // if you ask for HWND, it will be created
like image 156
Chris Peterson Avatar answered Sep 28 '22 02:09

Chris Peterson