我有必須含有大量和連續地進入列表視圖控件中的項的應用程序:System.argumentoutofrangeexception而調用Listviewitems使用迭代
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
deg_loadfile load = new deg_loadfile(loadfile);
load.BeginInvoke(new AsyncCallback(loadcallback),null);
}
void countfile() {
int listcount = listView1.Items.Count;
for (int x = 0; x < listcount; x++) {
listView1.BeginInvoke((MethodInvoker)delegate {
listView1.Items[x].SubItems[1].Text = "ok";
listView1.Items[x].SubItems[2].Text = "ok";
listView1.Items[x].SubItems[3].Text = "done";
},x);
}
}
void countcallback(IAsyncResult ae) {
MessageBox.Show("count finished");
}
delegate void deg_count();
void loadcallback(IAsyncResult ae) {
MessageBox.Show("finished");
}
delegate void deg_loadfile();
void loadfile() {
string file = File.ReadAllText("hughlist.txt");
string[] files = Regex.Split(file,"\n");
foreach (string str in files) {
listView1.BeginInvoke((MethodInvoker)delegate {
ListViewItem item = new ListViewItem(str);
item.SubItems.Add("");
item.SubItems.Add("");
item.SubItems.Add("");
listView1.Items.Add(item);
},str);
}
}
private void button2_Click(object sender, EventArgs e)
{
deg_count count = new deg_count(countfile);
count.BeginInvoke(new AsyncCallback(countcallback),null);
}
上面的代碼拋出system.argumentoutofrangeexception(請參見下圖)
鏈接圖像:http://i.stack.imgur.com/WJ7sA.png
迭代已經超過了我所給出的條件下,爲什麼會發生(注:在我的情況,我必須用「爲」而不是「的foreach」或其他枚舉)?
THX
UPDATE: THX到@saruman的答案(關鍵字是 「進入修改封」),我已經更新的代碼如下
for (int x = 0; x < listcount; x++) {
var x1=x;
listView1.BeginInvoke((MethodInvoker)delegate
{
listView1.Items[x1].SubItems[1].Text = "ok";
listView1.Items[x1].SubItems[2].Text = "ok";
listView1.Items[x1].SubItems[3].Text = "done";
}, x1); }
循環是否至少執行一次? –
@ l19是的,它執行一次然後拋出異常 – mysticcode