c# - How can solve "Cross-thread operation not valid"? -
I try to start multiple threads but I can not return it for error: cross- Thread operation is not valid: The 'ListBox1' thread was created to control external access from another thread.
MyCodes:
Public DataTable dTable; Public datatyla dtRowsCount; Thread T1; Thread Start ts1; Zero ExcelToSql () {// SelectDataFromExcel (); Ts1 = new threadstart (SelectDataFromExcel); T1 = new thread (ts1); T1.Start (); }
zero SelectDataFromExcel () {string connectionString = @ "provider = Microsoft.ACE.OLEDB.12.0; data source = C: \ source \ address.xlsx; extended properties = "" Excel 12.0; HDR = Yes; "" "; OleDbConnection Excel Connection = New OleDbConnection (connectionString); String [] sheet = new string [] {"cepa1"}; ExcelConnection.Open (); // This code will open the Axel file. OndeB Command DB Command; OleDbDataAdapter Data Adapter; // progressBar1.Minimum = 1; Fresh (Sheets in Sheets) {DB Commands = New Oledib Commands ("" + "+ Sheet +"], Excel Connection from "Choose"); //progressbar1.maximum = CounterSupssex (Sheet) .ow calculation; // progressBar2 .Value = I + 1; System.Threading.Thread.Sleep (1000); ** listBox1.Items.Add ("Tablo ismi:" + sheet.ToUpper () + "Cert Adeti:" + CountRowsExcel (sheet). ; To.Truth () + ""); ** DataDetter = 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);} Excel Connection. Close (); excelConnection.Dispose ();}
Thread in the background is not allowed to access UI components.
In the forms, I include the code like this:
Private representative zero invokeAction (); Private Zero DoUI (InvokeAction call) {If (IsDisposed) {return; } If (invocuired) {try (call) (call); } Hold (invalid operation exception) {// handle error}} other {call (); }}
Then from my background thread I can code like this:
// MyVar = GetFromDb (); DoUI ((=) = & gt; {// Access UI component here listbox 1. items.ed (mover);}); // more thread
Comments
Post a Comment