zoukankan      html  css  js  c++  java
  • Thread is suspended; attempting to abort的错误处理

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

    以下代码重现了我的错误

    Code

    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了

  • 相关阅读:
    Android开发环境搭建全程演示(jdk+eclip+android sdk)
    mysql UDF接口 网络编程(代码改进版非阻塞,超时重传)
    HTTP_POST———使用mysql_udf与curl库完成http_post通信模块(mysql_udf,multi_curl,http,post)
    Linux自动更新时间
    CentOS下设置Mysql的root密码
    CentOS yum安装LAMP环境
    Nagios远程监控软件的安装与配置详解
    Android开发之旅:环境搭建及HelloWorld
    CentOS 6.3安装配置LAMP服务器(Apache+PHP5+MySQL)
    c#,winform,show,showdialog,子窗体,父窗体,传值,输入正确
  • 原文地址:https://www.cnblogs.com/lexus/p/1263283.html
Copyright © 2011-2022 走看看