Cross-thread operation not valid

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • phantom2000
    New Member
    • Oct 2016
    • 3

    #1

    Cross-thread operation not valid

    I'm using the below code to update a progress bar.

    Code:
    if (read_success == true && global_variables.csvtext == "not found")
                   {
                        this.Unknown_Device.Text = "Writing CSV. Please wait.";
                        backgroundWorker1.RunWorkerAsync();
                   }
    
    rivate void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
            {
                for (int i = 0; i <= 100; i++ )
                {
                    simulateHeavyWork();
                    backgroundWorker1.ReportProgress(i);
                }
            }
            private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
            {
                this.csvprogressbar.Value = e.ProgressPercentage;
            }
            private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
            {
                writecsv(null, null);
            }
            private void simulateHeavyWork() 
            {
                Thread.Sleep(40);
            }
    But when I debug the program on Visual Studio it breaks on where ever I have used text box controls by giving the below message.

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

    I read this issue on the Internet but I can't really figure how to change the code to get around this issue since I'm a total newbie to C# programming.

    Appreciate if I can get some help with modifying the code to make the application run properly.

    Thanks.
  • Frinavale
    Recognized Expert Expert
    • Oct 2006
    • 9749

    #2
    Tried this code based on yours:
    Code:
        private ComponentModel.BackgroundWorker backgroundWorker1;
    
        private void MainWindow_Loaded(Object sender,System.Windows.RoutedEventArgs e){
            backgroundWorker1 = new ComponentModel.BackgroundWorker();
            backgroundWorker1.WorkerReportsProgress = true;
            backgroundWorker1.DoWork += new DoWorkEventHandler(backgroundWorker1_DoWork);
            backgroundWorker1.ProgressChanged += new ProgressChangedEventHandler(backgroundWorker1_ProgressChanged);
            backgroundWorker1.RunWorkerCompleted += new RunWorkerCompletedEventHandler(backgroundWorker1_RunWorkerCompleted);
            backgroundWorker1.RunWorkerAsync();
        }
        private void backgroundWorker1_DoWork(Object sender, ComponentModel.DoWorkEventArgs e){
            for(int i=0; i<100; i++){
                simulateHeavyWork();
                backgroundWorker1.ReportProgress(i);
            }
        }
        private void backgroundWorker1_ProgressChanged(Object sender, ComponentModel.ProgressChangedEventArgs e){
            this.csvprogressbar.Value = e.ProgressPercentage;
        }
        private Sub backgroundWorker1_RunWorkerCompleted(Object sender, ComponentModel.RunWorkerCompletedEventArgs e){
    
        }
        private void simulateHeavyWork(){
            System.Threading.Thread.Sleep(40);
        }
    It works fine. However, there is no reference to textbox1 in the above code so I could not reproduce your error based on what you provided.


    Maybe you should check out the documentation for the Backgroundworke r class. At the bottom are code examples that explain how to use it.
    Last edited by Frinavale; Oct 27 '16, 02:56 PM.

    Comment

    • phantom2000
      New Member
      • Oct 2016
      • 3

      #3
      Below is my full code. Program starts to break on model.Text = Model_Number. And then it goes to the other label controls.

      Code:
      using MobileDevice;
      using System;
      using System.Collections.Generic;
      using System.ComponentModel;
      using System.Data;
      using System.Drawing;
      using System.IO;
      using System.Linq;
      using System.Net;
      using System.Text;
      using System.Text.RegularExpressions;
      using System.Threading.Tasks;
      using System.Windows.Forms;
      using System.Diagnostics;
      using System.Threading;
      
      namespace MobileDevic
      {
          public partial class Main_Window : Form
          {
              iPhone iphone = new iPhone();
              public static string Model_Number, Colour_, Capacity_, Model_Name;
              public static string iDevice = "iPhone";
              public static bool read_success;
              string[] csvarray = new string[4];
      
              public Main_Window()
              {
                  InitializeComponent();
      
              }
              private void Form1_Load(object sender, EventArgs e)
              {
                  serial.Text = "";
                  Version.Text = "";
                  Colour.Text = "";
                  Capacity.Text = "";
                  imei.Text = "";
                  model.Text = "";
                  Unknown_Device.Text = "";
                  toolStripStatusLabel1.Text = "Waiting for iPhone...";
                  iphone.Connect += new MobileDevice.ConnectEventHandler(getInfo);
                  iphone.Disconnect += new MobileDevice.ConnectEventHandler(remove);
                  iphone.RecoveryModeEnter += new EventHandler(recovfound);
                  if (iphone.IsConnected == true)
                  {
                      getInfo(null, null);
                      readcsv_exists();
                      if (read_success == true && global_variables.csvtext == "not found")
                      {
                          this.Unknown_Device.Text = "Writing CSV. Please wait.";
                          backgroundWorker1.RunWorkerAsync();
                      }
                  }
              }
              private void recovfound(object sender, EventArgs args)
              {
                  MessageBox.Show("A device in recovery mode has been found");
              }
              private void remove(object sender, ConnectEventArgs args)
              {
                  this.Invoke((MethodInvoker)delegate
                  {
                      serial.Text = "";
                      Version.Text = "";
                      Colour.Text = "";
                      Capacity.Text = "";
                      imei.Text = "";
                      model.Text = "";
                      toolStripStatusLabel1.Text = "Waiting for iDevice...";
                  });
              }
              private void getInfo(object sender, EventArgs e)
              {
                  Model_Number = iphone.DeviceModelNumber;
                  model.Text = Model_Number;
                  global_variables.model_number_global = Model_Number;
                  imei.Text = iphone.InternationalMobileEquipmentIdentity;
                  serial.Text = iphone.DeviceSerial;
      
                  toolStripStatusLabel1.Text = "iPhone running iOS " + this.iphone.DeviceVersion + " connected.";
                  var fileStream = new FileStream(Directory.GetCurrentDirectory() + @"\DvDB.ADB", FileMode.Open, FileAccess.Read);
                  using (var streamReader = new StreamReader(fileStream, Encoding.UTF8))
                  {
                      string line;
                      while ((line = streamReader.ReadLine()) != null)
                      {
                          if (line.Contains("" + Model_Number))
                          {
      
      
                              string[] phoneinfo = line.Split(' ');
                              iDevice = phoneinfo[0];
                              Model_Name = phoneinfo[1];
                              Colour_ = phoneinfo[2];
                              Capacity_ = phoneinfo[3];
      
                              Version.Text = iDevice + " " + Model_Name;
                              Colour.Text = Colour_;
                              Capacity.Text = Capacity_;
                              Unknown_Device.Text = "";
                              read_success = true;
                              break;
                          }
                          else
                          {
                              read_success = false;
                              Version.Text = "Unknown Device";
                              Colour.Text = "Unknown Device";
                              Capacity.Text = "Unknown Device";
                              Unknown_Device.Text = "Please add device to database";
                          }
                      }
                  }
              }
              private void Add_Click(object sender, EventArgs e)
              {
                  if (read_success == false)
                  {
                      Add_Device Add_Window = new Add_Device();
                      Add_Window.Show();
                      this.Hide();
                  }
                  else
                  {
                      MessageBox.Show("Device already in the databse.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                  }
      
              }
              private void Exit_Click(object sender, EventArgs e)
              {
                  Application.Exit();
              }
              private void writecsv(object sender, EventArgs e)
              {
                  csvarray[0] = "" + iDevice + " " + Model_Name;
                  csvarray[1] = Capacity.Text;
                  csvarray[2] = imei.Text;
                  File.WriteAllText(@"Devices.csv", string.Join(",", csvarray));
                  MessageBox.Show("Data successfully written to CSV.", "Success", MessageBoxButtons.OK, MessageBoxIcon.Information, MessageBoxDefaultButton.Button1);
              }
              private void readcsv_exists()
              {
                  string CSVline = File.ReadLines(@"Devices.csv").First();
                  if (CSVline.Contains("" + imei.Text))
                  {
                      global_variables.csvtext = "Found";
                  }
                  else
                  {
                      global_variables.csvtext = "not found";
                  }
              }
              private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
              {
                  for (int i = 0; i <= 100; i++)
                  {
                      simulateHeavyWork();
                      backgroundWorker1.ReportProgress(i);
                  }
              }
              private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
              {
                  this.Invoke((MethodInvoker)delegate
                  {
                      csvprogressbar.Value = e.ProgressPercentage;
                  });
      
              }
              private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
              {
                  writecsv(null, null);
              }
              private void simulateHeavyWork()
              {
                  Thread.Sleep(40);
              }
          }
      }

      Comment

      • Frinavale
        Recognized Expert Expert
        • Oct 2006
        • 9749

        #4
        Ah Ok, I see what you are doing.

        It's not your background worker that is causing the problem it's the device connection that is running on a different thread.

        You need to make sure that you are accessing your form's controls in a thread safe way when you are using multiple threads in your application. Check out this MSDN article about How to: Make Thread-Safe Calls to Windows Forms Controls

        Here is a simplified project that demonstrates how to set the Text property of a text box in a Thread Safe way.

        Just create a new Windows Forms project called "WindowsFormsApp lication1" and copy and paste this code into the Form1.cs code.


        Code:
        using System;
        using System.Collections.Generic;
        using System.ComponentModel;
        using System.Data;
        using System.Drawing;
        using System.Linq;
        using System.Text;
        using System.Windows.Forms;
        
        namespace WindowsFormsApplication1
        {
            public partial class Form1 : Form
            {
                //Dynamically creating controls so that it is easy for demonstration purposes
                //All you have to do is create a new Windows Forms application
                //called WindowsFormsApplication1 and copy paste this code to see the working demonstration
        
                private System.ComponentModel.BackgroundWorker backgroundWorker1; //will do work on another thread in the background
                private TextBox progressNumber; //a TextBox that the background worker will set while doing work (accessing it across threads)
                private Label progressNumberPrompt;//just a prompt for the TextBox
                private ProgressBar csvProgressBar;//the progress bar
        
                public Form1()
                {
                    InitializeComponent();
                    
                    //Initializing dynamic controls
                    progressNumberPrompt = new Label();
                    progressNumberPrompt.Text = "Progress Number";
                    progressNumberPrompt.Location = new Point(13, 13);
                    progressNumber = new TextBox();
                    progressNumber.Location = new Point(115, 10);
                    csvProgressBar = new ProgressBar();
                    csvProgressBar.Width = 250;
                    csvProgressBar.Location = new Point(12, 227);
                    csvProgressBar.Visible = false;
                    this.Controls.Add(progressNumberPrompt);
                    this.Controls.Add(progressNumber);
                    this.Controls.Add(csvProgressBar);
        
                    backgroundWorker1 = new System.ComponentModel.BackgroundWorker();
                    backgroundWorker1.WorkerReportsProgress = true;
                    backgroundWorker1.DoWork += new DoWorkEventHandler(backgroundWorker1_DoWork);
                    backgroundWorker1.ProgressChanged += new ProgressChangedEventHandler(backgroundWorker1_ProgressChanged);
                    backgroundWorker1.RunWorkerCompleted += new RunWorkerCompletedEventHandler(backgroundWorker1_RunWorkerCompleted);
                }
                private void Form1_Load(object sender, EventArgs e)
                {   //Starting the process
                    progressNumber.Text = "";
                    csvProgressBar.Visible = true;
                    backgroundWorker1.RunWorkerAsync();
                }
        
                //Does the work for the background worker
                private void backgroundWorker1_DoWork(Object sender, System.ComponentModel.DoWorkEventArgs e)
                {          
                    for (int i = 0; i <= 100; i++)
                    {
                        simulateHeavyWork();
                        SetText(i.ToString());//using the SetText method to set the text of the TextBox in a thread save manner
                        backgroundWorker1.ReportProgress(i);
                    }
                }
        
        
                // This delegate enables asynchronous calls for setting
                // the text property on a TextBox control.
                delegate void SetTextCallback(string text);
        
                
                // This method demonstrates a pattern for making thread-safe
        		// calls on a Windows Forms control. 
        		//
        		// If the calling thread is different from the thread that
        		// created the TextBox control, this method creates a
        		// SetTextCallback and calls itself asynchronously using the
        		// Invoke method.
        		//
        		// If the calling thread is the same as the thread that created
        		// the TextBox control, the Text property is set directly. 
                private void SetText(string text)
                {
                    // InvokeRequired required compares the thread ID of the
                    // calling thread to the thread ID of the creating thread.
                    // If these threads are different, it returns true.
                    if (this.progressNumber.InvokeRequired)
                    {
                        SetTextCallback d = new SetTextCallback(SetText);
                        this.Invoke(d, new object[] { text });
                    }
                    else
                    {
                        this.progressNumber.Text = text;
                    }
                }
        
                //Showing progress change
                private void backgroundWorker1_ProgressChanged(Object sender, System.ComponentModel.ProgressChangedEventArgs e)
                {
                    this.csvProgressBar.Value = e.ProgressPercentage;
                }
        
                //Finished: hiding progress bar
                private void backgroundWorker1_RunWorkerCompleted(Object sender, System.ComponentModel.RunWorkerCompletedEventArgs e)
                {
                    csvProgressBar.Visible = false;
                }
        
                //Simulating work
                private void simulateHeavyWork()
                {
                    System.Threading.Thread.Sleep(40);
                }
        
            }
        }

        Comment

        Working...