在自制线程池的过程中遇到这样一个情景:需要中断一个可能是正在执行的任务,这个任务也可能任务队列中,由于是线程池,任务执行完后线程不是消失的而是继续等待接收下一个任务的,我使用的是Thread.Suspend来暂停线程当线程完成一项任务后,这时候如果使用Thread.Abort来中断这个ThreadState为Suspended的线程是会报错的。
以下代码重现了我的错误
![ContractedBlock.gif](https://i-blog.csdnimg.cn/blog_migrate/0be121fa5b8988fbabbbc526af3b0fc0.gif)
![ExpandedBlockStart.gif](https://i-blog.csdnimg.cn/blog_migrate/34031c708bfe702fe82d01ff5c6593aa.gif)
<!--<br /><br />Code highlighting produced by Actipro CodeHighlighter (freeware)<br />http://www.CodeHighlighter.com/<br /><br />-->using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
namespace ThreadPoolTest
{
class Class5
{
static void Main(string[] args)
{
Thread thd=new Thread(new ThreadStart(test));
thd.Start();
Thread.Sleep(10000);
thd.Abort();
Console.WriteLine();
Console.ReadLine();
}
private static void test()
{
Console.WriteLine("aa");
Thread.CurrentThread.Suspend();
Console.WriteLine("aa");
}
}
}
google许久,发现一篇英文http://www.code-magazine.com/article.aspx?quickid=0309071&page=4描述的非常清楚,其中有如下一段:
If Abort() is called before the thread is started, .NET will never start the thread once Thread.Start() is called. If Thread.Abort() is called while the thread is blocked (either by calling Sleep(), or Join(), or if the thread is waiting on one of the .NET synchronization objects), .NET unblocks the thread and throws ThreadAbortException in it. However, you cannot call Abort() on a suspended thread. Doing so will result on the calling side with an exception of type ThreadStateException, with the error message "Thread is suspended; attempting to abort." In addition, .NET will terminate the suspended thread without letting it handle the exception
就是说线程的状态是Suspended的时候,是不能使用Thread.Abort来中止的,那我们的情况怎么处理呢,我们换了一个思路,既然线程的状态已经是 Suspended了为什么我们还要Abort它呢,将它再次放入线程池为后续任务工作不是更好吗?
于是加一个条件判断
if(Thread.ThreadState==ThreadState.Suspended):
pass
这样就ok了