Home > DeveloperSection > Forums > How to handle 'Cross thread exception' in winforms
Anupam Mishra

Total Post:135

Points:949
Posted on    January-18-2016 11:38 PM

 C# C#  .NET 
Ratings:


 1 Reply(s)
 220  View(s)
Rate this:
I have created one listview and display items with the using BackgroundWorker thread , But it will thrown an 'Cross thread exception ' in winforms.
Please give me a solution.

thank you.


Anupam Mishra

Total Post:135

Points:949
Posted on    January-19-2016 6:34 AM

As we say i am using a BackgroundWorker thread in a winforms and try to add item in DoWork method. So, for this situation we use code similar like this. it is working:

  private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
    {
        var test = new ListViewItem("item");
        backgroundWorker1.ReportProgress(0, test);
     }
  private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
    {
        listView1.Items.Add((ListViewItem)e.UserState);
    }
or
// avoid exception 'Cross thread exception'  if we using this

ListViewItem _item = new ListViewItem();

     if (listView1.InvokeRequired)

                    listView1.Invoke(new MethodInvoker(delegate

                    {

           listView1.Items.Add(_item);          

                    }));

                else

          listView1.Items.Add(_item);


Don't want to miss updates? Please click the below button!

Follow MindStick