让我带这另一个刺...
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