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了

  • 相关阅读:
    东芝开发板驱动OLED模块显示LOGO图片
    东芝MCU实现位带操作
    使用系统定时器SysTick实现精确延时微秒和毫秒函数
    VC++调试错误的解决方案
    #pragma once与 #ifndef的区别
    strcmp()字符串比较函数用法
    C、C++中的static和extern关键字
    error LNK1169 找到一个或多个多重定义的符号的解决方法
    vs2013编译obs源码
    Qt线程—QThread的使用--run和movetoThread的用法
  • 原文地址:https://www.cnblogs.com/lexus/p/1263283.html
Copyright © 2011-2022 走看看