讓我帶這另一個刺...
1)拖動一個ListView到窗體
2)一個BackgroundWorker拖到窗體
3)創建的方法不要通過ListViewItem集合
private void LoopThroughListItems()
{
foreach (ListViewItem i in listView1.CheckedItems)
DoSomething();
}
4)添加代碼來調用LoopThroughListItems()BackgroundWorker的的DoWork的事件
0123內循環
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
LoopThroughListItems();
}
5)在你的窗體加載 - 執行主線程代碼(它的工作原理),那麼backgroundWorkder線程(失敗)
private void Form1_Load(object sender, EventArgs e)
{
// Try it on the UI Thread - It works
LoopThroughListItems();
// Try it on a Background Thread - It fails
backgroundWorker1.RunWorkerAsync();
}
6)修改代碼以使用IsInvokeRequired /調用
private void LoopThroughListItems()
{
// InvokeRequired == True when executed by non-UI thread
if (listView1.InvokeRequired)
{
// This will re-call LoopThroughListItems - on the UI Thread
listView1.Invoke(new Action(LoopThroughListItems));
return;
}
foreach (ListViewItem i in listView1.CheckedItems)
DoSomething();
}
7.)再次運行應用程序 - 現在它在UI線程和非UI線程上工作。
這解決問題。檢查IsInvokeRequired /調用是你習慣了很多常見的模式(這就是爲什麼它是包含在所有控件)。如果你正在做的所有的地方,你可以做的很漂亮,敷了這一切 - 這裏描述:Automating the InvokeRequired code pattern
可能的重複:http://stackoverflow.com/questions/6092519/winforms-thread-safe-control-access – zmbq
如果您可以使用'BackgroundWorker',您表單中的每個控件都已經可讀... – Marco
向我們展示您正在使用的代碼請... – Marco