110,574
社区成员
发帖
与我相关
我的任务
分享
Thread[] t1=new Thread[10];
for (int i = 0; i < t1.Length; i++)
{
t1[i] = new Thread(new ThreadStart(delegate
{
//
//Do something......
//Do something......
//Do something......
//
//当循环到最后一次的时候,i会变成10,那for循环就肯定不会再执行下去,但这里的i也会变成10,就会报索引超出数组界限的错误。
//而且在for循环里面的所有的i都会报这个错误。
string str = table.Rows[i]["str"].ToString();
}
));
t1[i].Start();
Thread.Sleep(1000);
}
Thread[] t1 = new Thread[10];
for (int i = 0; i < t1.Length; i++)
{
t1[i] = new Thread(() =>
{
Console.WriteLine("the i is " + i+",thread is :"+Thread.CurrentThread.Name);
})
{
Name = "thread"+i
};
t1[i].Start();
Thread.Sleep(1000);
}
结果:
the i is 0,thread is :thread0
the i is 1,thread is :thread1
the i is 2,thread is :thread2
the i is 3,thread is :thread3
the i is 4,thread is :thread4
the i is 5,thread is :thread5
the i is 6,thread is :thread6
the i is 7,thread is :thread7
the i is 8,thread is :thread8
the i is 9,thread is :thread9
请按任意键继续. . .[/quote]
怎么说呢,只是他写了睡眠而已,1000ms保证了子线程代码执行完成
Thread[] t1 = new Thread[10];
for (int i = 0; i < t1.Length; i++)
{
t1[i] = new Thread(() =>
{
Console.WriteLine("the i is " + i+",thread is :"+Thread.CurrentThread.Name);
})
{
Name = "thread"+i
};
t1[i].Start();
Thread.Sleep(1000);
}
结果:
the i is 0,thread is :thread0
the i is 1,thread is :thread1
the i is 2,thread is :thread2
the i is 3,thread is :thread3
the i is 4,thread is :thread4
the i is 5,thread is :thread5
the i is 6,thread is :thread6
the i is 7,thread is :thread7
the i is 8,thread is :thread8
the i is 9,thread is :thread9
请按任意键继续. . .int index = i;
做的一样。
如果说4.5之类的给你自动将参数做了栈复制和转换,那只能说它可能放弃类之前“可以改变共享变量”这个特点。丢掉了之前的特性,而默认地改变为现在的新特性。
for (int i = 0; i < t1.Length; i++)
{
int index = i;
t1[i] = new Thread(new ThreadStart(delegate
{
//
//Do something......
//Do something......
//Do something......
//
//当循环到最后一次的时候,i会变成10,那for循环就肯定不会再执行下去,但这里的i也会变成10,就会报索引超出数组界限的错误。
//而且在for循环里面的所有的i都会报这个错误。
string str = table.Rows[index]["str"].ToString();
}
));
t1[i].Start();
Thread.Sleep(1000);
}
Thread[] thread = new Thread[dataGridViewX1.Rows.Count];
for (int i = 0; i < dataGridViewX1.Rows.Count; i++)
{
//以前一直用new Thread(new ThreadStart(delegate{} 这种写法
thread[i] = new Thread(new ThreadStart(delegate
{
ThreadMethod(i);
}));
thread[i].Start();
Thread.Sleep(1000);
}
for (int i = 0; i < dataGridViewX1.Rows.Count; i++)
{
//现在用new ParameterizedThreadStart(ThreadMethod),不知这两个有什么区别,利弊?感觉效果都一样
thread[i] = new Thread(new ParameterizedThreadStart(ThreadMethod));
thread[i].Start(i);
Thread.Sleep(1000);
}
Thread[] thread = new Thread[dataGridViewX1.Rows.Count];
for (int i = 0; i < dataGridViewX1.Rows.Count; i++)
{
thread[i] = new Thread(new ParameterizedThreadStart(DoYourWork));
thread[i].Start(i);
Thread.Sleep(1000);
}
public void DoYourWork(object index)
{
//你的代码
}