HOW TO HANDLE 'CROSS THREAD EXCEPTION' IN WINFORMS

Anupam Mishra

Total Post:135

Points:949
Posted by  Anupam Mishra
C#  .NET 
C#
 453  View(s)
Ratings:
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.
  1. Anupam Mishra

    Post:135

    Points:949
    Re: How to handle 'Cross thread exception' in winforms

    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);

Answer

NEWSLETTER

Enter your email address here always to be updated. We promise not to spam!