"Cross-thread operation not valid" without threading!!

P

Pieter Coucke

Hi,

In my VB.NET 2005 application I'm generating and sending emails using the
outlook-object model (2003). When a mail is Send (MailObject_Send), I raise
an event in a global class, that is caught by all my forms that than refresh
the lists with emails.

But on the moment I do a MyDataGrid.DataSource = nothing, I get this
"Cross-thread operation not valid"-exception:

The problem is: I'm not using delegates, backgroundworkers or whatever! Why
does this happen? and what is the solution?

Thanks a lot in advance,

Pieter

The full exception:
A first chance exception of type 'System.InvalidOperationException' occurred
in System.Windows.Forms.dll

Additional information: Cross-thread operation not valid: Control ''
accessed from a thread other than the thread it was created on.
 
D

Dmytro Lapshyn [MVP]

Hi,

It can be that you receive the MailObject_Send event on a background thread.
If this is the case, check the InvokeRequired property on MyDataGrid and if
it's true, use MyDataGrid.Invoke to run the data source update code on the
UI thread.

BTW it would be better to use the SetDataBinding method to update the grid's
data source.
 
G

gumson

Hi

You cannot perform any action on Control based object from another
thread than the GUI thread unless you specify the
Control.CheckForIllegalCrossThreadCalls property as false. This is
however dangerous and can cause unspecified results. What you need to
do is to check for the Control.InvokeRequired property. If this
property is tru you'll need to call on Invoke for the same method.

Example:

private delegate void DoWorkHandler();

class MyForm : Form
{
// Method called from another thread than the GUI
DoWork()
{
if (this.InvokeRequired)
{
Invoke(new DoWorkHandler(this.DoWork), new object[] {}); //
here you put parameters needed for the DoWork method
}
else
{
// Perform gui thread actions
}
}

}


Thanks
Gumson
 
P

Pieter Coucke

Dmytro Lapshyn said:
It can be that you receive the MailObject_Send event on a background
thread.

And why can this happen? I used a Delegate now, but I still don't get why I
had this thread-problem :-S
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top