How can solve “Cross-thread operation not valid”?

2019-01-15 21:17发布

i try to start multi Thread but i can not it returns to me error: Cross-thread operation not valid: 'listBox1' thread was created to control outside access from another thread was.

MyCodes:

 
  public DataTable dTable;
        public DataTable dtRowsCount;
        Thread t1;
        ThreadStart ts1;
  void ExcelToSql()
        {
           // SelectDataFromExcel();
            ts1 = new ThreadStart(SelectDataFromExcel);
            t1 = new Thread(ts1);
            t1.Start();
        }
   void SelectDataFromExcel()
        {
            string connectionString = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Source\Addresses.xlsx;Extended Properties=""Excel 12.0;HDR=YES;""";
            OleDbConnection excelConnection = new OleDbConnection(connectionString);
                      string[] Sheets = new string[] { "Sayfa1"};
            excelConnection.Open(); // This code will open excel file.            
            OleDbCommand dbCommand;
            OleDbDataAdapter dataAdapter;
          //  progressBar1.Minimum = 1;

            foreach (var sheet in Sheets)
            {
                dbCommand = new OleDbCommand("select * From[" + sheet + "$]", excelConnection);
                //progressBar1.Maximum = CountRowsExcel(sheet).Rows.Count;
               // progressBar2.Value = i + 1;
                System.Threading.Thread.Sleep(1000);
                **listBox1.Items.Add("Tablo ismi: "+sheet.ToUpper()+"Satır Adeti: "+CountRowsExcel(sheet).Rows.Count.ToString()+" ");**
                dataAdapter = new OleDbDataAdapter(dbCommand);
                dTable = new DataTable();
                dataAdapter.Fill(dTable);
                dTable.TableName = sheet.ToUpper();
                dTable.Dispose();
                dataAdapter.Dispose();
                dbCommand.Dispose();
                ArrangedDataList(dTable);
                FillSqlTable(dTable, dTable.TableName);
            }

            excelConnection.Close();
            excelConnection.Dispose();
        }

3条回答
女痞
2楼-- · 2019-01-15 21:27

The thread in background is not allowed to access the UI components.

In multithreaded forms, I include code like this:

    private delegate void InvokeAction();
    private void DoUI(InvokeAction call) {
        if (IsDisposed) {
            return;
        }
        if (InvokeRequired) {
            try {
                Invoke(call);
            } catch (InvalidOperationException) {
                // Handle error
            }
        } else {
            call();
        }
    }

Then from my background thread I can code like this:

    // Stuff in other thread
    myVar = GetFromDb();
    DoUI(() => { 
       // Access UI components here 
       listBox1.Items.Add(myVar);
    });
    // More other thread 
查看更多
等我变得足够好
3楼-- · 2019-01-15 21:31

You cannot update a UI component from a non-UI thread. Use TaskScheduler.FromCurrentSynchronizationContext to marshal the call to the UI thread.

查看更多
戒情不戒烟
4楼-- · 2019-01-15 21:47

A control created in the UI thread cannot be accessed in another thread in normal fashion. Please create a delegate and invoke the delegate using control.Invoke.

The method sample provided below can be used to enable visibility on a button regardless of the thread context you are in.

private void EnableButtonVisibility( Button btn, bool enable)    
{     
    if ( !btn.InvokeRequired )    
    {    
 btn.Visible = enable;    
    }   
    else    
    {    
        btn.Invoke( new EnableButtonVisibilityHandler( EnableButtonVisibility ), btn, enable );    
    }    
}    
delegate void EnableButtonVisibilityHandler( Button btn, bool enable);
查看更多
登录 后发表回答