2017-09-20 20 views
0

我必須檢查列表框的SelectedIndex是否在BackgroundWorker最後一個索引,但由於我正在檢查列表框(這是在GUI線程上)從BackgroundWorker我得到這個錯誤:檢查是否listbox.SelectedIndex ==從BackBoxWorker的列表框的ListBox.Items.Count

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

這是我的代碼:

if (listBox1.SelectedIndex == listBox1.Items.Count) 
{ 
//code here 
} 

我怎麼可能讓這個if語句工作而不GUI線程上?

回答

-1

這基本上發生在從另一個線程訪問表單屬性時,這就是引發此異常的原因。您的UI操作必須在擁有的線程上執行。這裏

int intIndex = 0; 
int intCount = 0; 
     if (listBox1.InvokeRequired) 
     { 
      listBox1.Invoke(new MethodInvoker(delegate { intIndex = listBox1.SelectedIndex ; })); 
     } 

     if (listBox1.InvokeRequired) 
     { 
      listBox1.Invoke(new MethodInvoker(delegate { intCount = listBox1.Items.Count; })); 
     } 

那麼你的條件:

你可以做到這一點

 if (intIndex == intCount) 
     { 
      // TODO: Business Logic 
     } 

或者你也可以做到這一點速戰速決,但對生產不可取的,但你可以做開發。您可以在您的構造函數上添加這個表單:

CheckForIllegalCrossThreadCalls = false; 
+0

第一個人應該*永遠不會*將CheckForIllegalCrossThreadCalls設置爲false。所有這一切都是延遲發現使用來自錯誤線程的控制將不可避免地導致的問題。 –

+0

謝謝,這正是我正在尋找的。當我回家的時候會去測試它! – Thomas

+0

好吧,讓我知道它是否有效,如果這回答你的問題,你可以接受它作爲答案,謝謝! @Thomas –