Go Premium for a chance to win a PS4. Enter to Win

x
?
Solved

Implmenting Threading (in Winforms C#)- Getting Error - Cross-thread operation not valid

Posted on 2008-06-22
5
Medium Priority
?
2,248 Views
Last Modified: 2008-07-03
Hi,

 

I am trying to implement Threading in my application. One of my method ia taking 2 to 3 mins time for getting data from SQL Server. So I have Implemented Threading for this.

 

But I am getting error InvalidOperation Exception -  Cross-thread operation not valid: Control 'dataGridView1' accessed from a thread other than the thread it was created on.

 

Here is my sample code.

 

public partial class frmEmployee : Form

{

public frmEmployee()

{

InitializeComponent();

}

 

protected override void OnLoad(EventArgs e)

{


base.OnLoad(e);

}

private void button1_Click(object sender, EventArgs e)

{


ThreadPool.QueueUserWorkItem(new WaitCallback(GetEmployeeData));


}

private void GetEmployeeData(Object stateInfo)

{

DataAccessLayer db = new DataAccessLayer();

System.Linq.IQueryable<Employee> emp = db.GetEmployee();

dataGridView1.DataSource = emp;


}

private void EmployeeData()

{

DataAccessLayer db = new DataAccessLayer();

System.Linq.IQueryable<Employee> emp = db.GetEmployee();

dataGridView1.DataSource = emp;

}

private void button2_Click(object sender, EventArgs e)

{

SecondMethod();

}

private static void SecondMethod()

{

MessageBox.Show("This is my second test message");

}

}

 

After clicking Button1, I clicked Button2 which display me the message "This is my second test message".

But after that I am getting, Cross-thread operation not valid.

 

Please help me with this.

 

Thanks!!!

public partial class frmEmployee : Form
 
{
 
public frmEmployee()
 
{
 
InitializeComponent();
 
}
 
 
 
protected override void OnLoad(EventArgs e)
 
{
 
 
base.OnLoad(e);
 
}
 
private void button1_Click(object sender, EventArgs e)
 
{
 
 
ThreadPool.QueueUserWorkItem(new WaitCallback(GetEmployeeData));
 
 
}
 
private void GetEmployeeData(Object stateInfo)
 
{
 
DataAccessLayer db = new DataAccessLayer();
 
System.Linq.IQueryable<Employee> emp = db.GetEmployee();
 
dataGridView1.DataSource = emp;
 
 
}
 
private void EmployeeData()
 
{
 
DataAccessLayer db = new DataAccessLayer();
 
System.Linq.IQueryable<Employee> emp = db.GetEmployee();
 
dataGridView1.DataSource = emp;
 
}
 
private void button2_Click(object sender, EventArgs e)
 
{
 
SecondMethod();
 
}
 
private static void SecondMethod()
 
{
 
MessageBox.Show("This is my second test message");
 
}
 
}

Open in new window

0
Comment
Question by:r_pat72
  • 2
  • 2
5 Comments
 
LVL 18

Expert Comment

by:philipjonathan
ID: 21840053
I think the problem is with line 42
dataGridView1.DataSource = emp;

I don't think you can data bind a datagrid on a thread other than the thread where the control was created. You might want to perform data binding inside the OnLoad override, and just refresh the data (query from data source) during GetEmployeeData().
0
 
LVL 18

Expert Comment

by:carlnorrbom
ID: 21840076
It is illegal to make cross thread calls to the UI thread as far as I know, but You should be abe to override the default behaivor using:

private void GetEmployeeData(Object stateInfo)
 {
// Disable the checking for illegal crossthread calls
Control.CheckForIllegalCrossThreadCalls = false;
// Rest of code...
 DataAccessLayer db = new DataAccessLayer();
 System.Linq.IQueryable<Employee> emp = db.GetEmployee();
 dataGridView1.DataSource = emp;
 }

Just add the extra line to all method making cross thread calls. But notice that this is NOT the best solution, it's simply disabling the checking.
/Carl.
0
 
LVL 10

Accepted Solution

by:
margajet24 earned 2000 total points
ID: 21840205
       private void GetEmployeeData(Object stateInfo)
        {

            DataAccessLayer db = new DataAccessLayer();

            System.Linq.IQueryable<Employee> emp = db.GetEmployee();

            if (dataGridView1.InvokeRequired)
            {
                IAsyncResult result = dataGridView1.BeginInvoke(new MethodInvoker(delegate() { dataGridView1.DataSource = emp; }), new object[] { });

                dataGridView1.EndInvoke(result);
            }
            else
            {
                dataGridView1.DataSource = emp;
            }


        }
0
 
LVL 10

Expert Comment

by:margajet24
ID: 21840212
when updating controls on a separate thread, check first InvokeRequired because directly updating the properties of the control on another thread is not allowed.
0
 
LVL 18

Expert Comment

by:carlnorrbom
ID: 21840322
margajet24 is absolutely correct, I'm a VB guy, don't know the actual implementation i C#...
0

Featured Post

Free Tool: IP Lookup

Get more info about an IP address or domain name, such as organization, abuse contacts and geolocation.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Parsing a CSV file is a task that we are confronted with regularly, and although there are a vast number of means to do this, as a newbie, the field can be confusing and the tools can seem complex. A simple solution to parsing a customized CSV fi…
Calculating holidays and working days is a function that is often needed yet it is not one found within the Framework. This article presents one approach to building a working-day calculator for use in .NET.
Please read the paragraph below before following the instructions in the video — there are important caveats in the paragraph that I did not mention in the video. If your PaperPort 12 or PaperPort 14 is failing to start, or crashing, or hanging, …
Despite its rising prevalence in the business world, "the cloud" is still misunderstood. Some companies still believe common misconceptions about lack of security in cloud solutions and many misuses of cloud storage options still occur every day. …
Suggested Courses

877 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question