Thread is suspended; attempting to abort的错误处理

在自制线程池的过程中遇到这样一个情景:需要中断一个可能是正在执行的任务,这个任务也可能任务队列中,由于是线程池,任务执行完后线程不是消失的而是继续等待接收下一个任务的,我使用的是Thread.Suspend来暂停线程当线程完成一项任务后,这时候如果使用Thread.Abort来中断这个ThreadState为Suspended的线程是会报错的。

以下代码重现了我的错误

ContractedBlock.gif ExpandedBlockStart.gif Code
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了

posted on 2008-08-07 22:30  lexus 阅读( ...) 评论( ...) 编辑 收藏

转载于:https://www.cnblogs.com/lexus/archive/2008/08/07/1263283.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值