Click to See Complete Forum and Search --> : Cross thread operation not valid?


fusionstream
April 3rd, 2008, 07:38 AM
A DataGridView is created by the main class.

On aButtonClick, I want to start a new thread to automatically update the grid every 5 seconds.

I made the correct references and everything works (and is passed) smoothly. The only problem is that apparently, when I try to access the grid(which, again, was made in another thread, the debugger stops everything and tells me that an exception has occured as the cross thread operation is not valid.

In short, I want to edit a dataGridView made by threadA from threadB.

Any thoughts?

Alex F
April 3rd, 2008, 08:34 AM
You need to use Control.BeginInvoke or Control.Invoke methods. These methods asynchronously call control's methods in the context of thread which created this control. See code fragment here:

http://msdn2.microsoft.com/en-us/library/a06c0dc2.aspx

Suppose that Button_Click runs in the context of worker thread. DelegateMethod runs in the context of main UI thread, and can access form controls. See also Control.InvokeRequired Property.

It is also recommended to add line
Control.CheckForIllegalCrossThreadCalls = true;
to application startup code to get predictable failure on every illegal cross-thread call. Otherwise, behaviour is unpredictable: sometimes can succeed, sometimes fails.

fusionstream
April 4th, 2008, 08:06 PM
so it'll be something like in wrker thread, DataGridView1.Invoke(aFunctionICreated) where aFunctionICreated is a func in the main thread that will do the actual adding and stuff.

Hmm.. I just realised I should probably have done that in the first place but forgot since it was for testing. heh.

Cheers.

Alex F
April 5th, 2008, 12:54 AM
It is better to invoke your own form function, you can define function parameters according to your needs:

this->Invoke(aFunctionICreated);

aFunctionICreated - form function running in UI thread which can access DataGridView1 and any other control directly.