• 线程已被中止 “Thread was being aborted”


    线程已被中止- “Thread was being aborted”

    遇到过这个exception么? 这个exception是为什么而产生的呢?

    下面的代码段来自MSDN, 很有说明性.

    简单来说, 就是当进程还想继续执行的时候, 发现自己已经被调用过Abort方法了. 既然自己作为线程已经被中止, 就无法执行罗, 于是exception丢了出来.

    下面的代码来自MSDN, 说明问题:

    The following example demonstrates aborting a thread. The thread that receives the ThreadAbortException uses the ResetAbort method to cancel the abort request and continue executing.

       1: using System;
       2: using System.Threading;
       3: using System.Security.Permissions;
       4:  
       5: public class ThreadWork {
       6:     public static void DoWork() {
       7:         try {
       8:             for(int i=0; i<100; i++) {
       9:                 Console.WriteLine("Thread - working."); 
      10:                 Thread.Sleep(100);
      11:             }
      12:         }
      13:         catch(ThreadAbortException e) {
      14:             Console.WriteLine("Thread - caught ThreadAbortException - resetting.");
      15:             Console.WriteLine("Exception message: {0}", e.Message);
      16:             Thread.ResetAbort();
      17:         }
      18:         Console.WriteLine("Thread - still alive and working."); 
      19:         Thread.Sleep(1000);
      20:         Console.WriteLine("Thread - finished working.");
      21:     }
      22: }
      23:  
      24: class ThreadAbortTest {
      25:     public static void Main() {
      26:         ThreadStart myThreadDelegate = new ThreadStart(ThreadWork.DoWork);
      27:         Thread myThread = new Thread(myThreadDelegate);
      28:         myThread.Start();
      29:         Thread.Sleep(100);
      30:         Console.WriteLine("Main - aborting my thread.");
      31:         myThread.Abort();
      32:         myThread.Join();
      33:         Console.WriteLine("Main ending."); 
      34:     }
      35: }

    下面是输出结果:

    Thread - working.

    Main - aborting my thread.

    Thread - caught ThreadAbortException - resetting.

    Exception message: Thread was being aborted.

    Thread - still alive and working.

    Thread - finished working.

    Main ending.

  • 相关阅读:
    [bbk3153] 第62集 Chapter 15Application Tuning(02)
    [bbk3152] 第61集 Chapter 15Application Tuning(01)
    [bbk1190]第2集 Chapter 01Oracle Architectural
    PL/SQL高级Creating Packages (01)
    Statspack00
    [bbk3201] 第64集 Chapter 16Using Materialized Views 00
    该如何选择国外VPS
    优化升级logging封装RotatingFileHandler
    smtp ssl模式邮件发送与附件添加
    smtp outlook邮件发送非授权码模式
  • 原文地址:https://www.cnblogs.com/jiahuafu/p/3064668.html
Copyright © 2020-2023  润新知