2016-11-16 45 views
0

任何人都可以幫助我解決這個問題,因爲我不知道如何處理它。ListView Thread on C#

foreach (ListViewItem itemrow in this.listView1.Items) 
{ 
    result = PumpStart.SymbolAdd(itemrow.SubItems[0].Text.Trim()); 
    if(result != ResultCode.Ok) 
    { 
      Console.WriteLine("Error adding symbol. " + mgr.ErrorDescription(result)); 
    } 
} 

但是當我嘗試運行該程序,我有這樣的錯誤:

"An exception of type 'System.InvalidOperationException' occurred in System.Windows.Forms.dll but was not handled in user code

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

非常感謝你。

+0

這是正確的操作無效,因爲使用UI線程UI控件只能訪問和修改,對任何其他線程這將導致無效操作異常。考慮使用BackgroundWorker或Async-Await –

+0

看起來您正在訪問來自其他線程的UI元素。希望'MethodInvoker'能幫助你解決這個問題 –

+0

你能給我一個關於如何正確地做的例子嗎? – Raven

回答

0

如果listView1負責交叉線程錯誤,那麼您將需要使用它的InvokeBeginInvoke方法來訪問和修改數據。

正如documentation說:

The Method executes the specified delegate asynchronously on the thread that the control's underlying handle was created on.

換句話說:它拉要執行回其創建了要修改的Control線程的代碼段。

BeginInvoke需要Delegate作爲參數。在這個例子中Action是服務這一功能:

this.listView1.BeginInvoke(
      new Action(() => 
      { 
       foreach (ListViewItem itemrow in this.listView1.Items) 
       { 
        result = PumpStart.SymbolAdd(itemrow.SubItems[0].Text.Trim()); 
        if(result != ResultCode.Ok) 
        { 
         Console.WriteLine("Error adding symbol. " + mgr.ErrorDescription(result)); 
        } 
       } 
      }) 
);