List<Thread> tlist = new List<Thread>(); for (int i = 0; i < 5; i++) { Thread t = new Thread((x) => { while (true) { try {} catch (Exception) {} finally { for (int m = 0; m < 10000; m++) {
} } } }); t.Start(); tlist.Add(t); } for (int i = 0; i < tlist.Count; i++) { Thread t = tlist[i]; t.Abort(); } 跑跑
我是这样测试的List<Thread> tlist = new List<Thread>(); for (int i = 0; i < 3; i++) { Thread t = new Thread((x) => { while (true) { try { } catch (Exception) { } finally { for (int m = 0; m < 10000; m++) { Console.WriteLine("aaa"); } } } }); tlist.Add(t); } for (int i = 0; i < tlist.Count; i++) { Thread t = tlist[i]; t.Start(); } for (int i = 0; i < tlist.Count; i++) { Thread t = tlist[i]; t.Abort(); } }为什么结束不掉呢?
public void run()
{
while(flag)
{
}
}
主线程
public void start()
{
Thread t = new Thread(new ThreadStart(m));
t.start();
while(true)
{
//如果是为了不让主线程退出而做死循环的话,t线程就不会执行,因为执行到死循环这里就卡死了
}
}
for(int i=0; i<list.Count; i++)
{
Thread t = list[i];
t.Abort();
}这段代码最好是在主线程中执行。因为如果是非主线程的话,自身也是在此集合中的,可能没有结束掉所有的时候,就把自身结束掉了。所以,此时要有判断,结束掉所有其他399个后,再结束掉自身。
{
Thread t = list[i];
t.Abort();
}
写出这代码的人纯粹属于纸上谈兵的典型——马谡
public void run()
{
while(flag)
{
}
}
另外什么叫“不建议在主线程中使用死循环”,一看就知道概念不清晰。一个进程可以有多个无主次之分的前台线程,有多个无主次之分的后台线程,有一个默认的线程池,而各个线程之间都是独立的,没有什么主从之分。通过不同的线程,我可以同时打开多个互相之间各不影响的窗口,每个窗口都用ShowDialog方式打开,但是谁都不妨碍谁。对于楼主的问题,不能使用线程池操作,如果你选择了线程池,那就意味着你将放弃对线程的任何干预。又由于你有多个线程要执行,也不适合用Thread类操作,那个虽然可以组成数组来存储线程集合,但是有更好的,那就是利用.NET4.0里新增的Task类,多任务管理。Task可以对多个任务同时进行等待、终止、设置超时等,功能非常强大。
{
Thread t = new Thread((x) =>
{
while (true)
{
try
{}
catch (Exception)
{}
finally
{
for (int m = 0; m < 10000; m++)
{
}
} }
});
t.Start();
tlist.Add(t);
} for (int i = 0; i < tlist.Count; i++)
{
Thread t = tlist[i];
t.Abort();
}
跑跑
{
Thread t = new Thread((x) =>
{
while (true)
{
try
{ }
catch (Exception)
{ }
finally
{
for (int m = 0; m < 10000; m++)
{
Console.WriteLine("aaa");
}
} }
});
tlist.Add(t);
} for (int i = 0; i < tlist.Count; i++)
{
Thread t = tlist[i];
t.Start();
} for (int i = 0; i < tlist.Count; i++)
{
Thread t = tlist[i];
t.Abort();
} }为什么结束不掉呢?