我嘗試使用backgroundworker
來實現增量搜索。在C#winform中輸入錯誤backgroundworker時發現錯誤
這樣的想法是在textbox
頂部的用戶類型,併爲每個按鍵,下方的listview
進行過濾,只包含包含用戶鍵入的字符的項目。
我最近了解到backgroundworker
組件,因此試圖用它來過濾和更新listbox
。
這是textbox
的事件代碼:
private void txtSearch_TextChanged(object sender, EventArgs e)
{
if (!backgroundWorker1.IsBusy)
{
backgroundWorker1.RunWorkerAsync();
}
}
和backgroundworker
事件:
private void backgroundWorker1_DoWork(object sender, System.ComponentModel.DoWorkEventArgs e)
{
if (txtSearch.Text != String.Empty)
{
GetTheListOfFiles();
listView.Items.Clear(); << Exception occurs here !
...... //some more code to populate the listview control
}
}
問題
當我鍵入到textbox
,我期待listbox
立即響應我的按鍵和顯示相應地放置過濾的數據。取而代之的是約8秒鐘的停頓,然後我得到這個錯誤:
我相信這個問題是我已經強調了一點,但我不知道如何解決它。是否backgroundworker
不能用於這個目的,或者我在執行中丟失了什麼? PS:我歡迎任何不同的方式來實現這一點。也許更有經驗的程序員有更好的解決方案嗎?
UPDATE
這裏是progresschanged
事件我使用:
private void backgroundWorker1_ProgressChanged(object sender, System.ComponentModel.ProgressChangedEventArgs e)
{
toolStripProgressBar1.Value = e.ProgressPercentage;
tsLabelTwo.Text = e.ProgressPercentage.ToString() + @"%";
}
感謝
[跨線程操作無效的可能重複:控制訪問從一個線程以外的線程創建](http://stackoverflow.com/questions/142003/cross-thread-operation-not-valid-control-accessed-from-a-thread-other-than-the ) – MickyD
BackgroundWorker的DoWork事件與您嘗試更新的UI控件位於不同的線程中。這是一個衆所周知的問題,如果您想更新控件,則需要提高在UI的同一線程中運行的ProgressChanged事件 – Steve
謝謝Steve,我添加了progresschanged事件代碼。新手問題:我如何知道哪些線程可以運行?歡呼 – Nick