中国开发网: 论坛: 程序员情感CBD: 贴子 80993
没脾气2x: .NET, 关于 Thread.Abort()
1. 正常情况的 ThreadAbortException 异常。

在主程序中 theThread.Abort() 后将引发线程中的 ThreadAbortException 异常。

根据 MSDN 对 ThreadAbortException 的描述,“ThreadAbortException 是一种可捕获的特殊异常”,在 catch 块的结尾处,既便不使用 throw 它仍将继续引发,这样可能经过所有上级 catch ,直至遇到 Thread.ResetAbort();

Thread.ResetAbort(); 取消为当前线程请求的 Abort(); 执行后 ThreadAbortException 不再继续引发。如果主程序再次调用 theThread.Abort(); ThreadAbortException 异常将再次引发。

2. Abort() 尚未 ResetAbort() 再次 Abort()

第二次 Abort() 不起作用。除非在第二次调用 Abort 前,已经执行了 ResetAbort();

3. 线程正进行于其它 finally 、catch 块中时

线程将在处理其 finally 外中的内容后引发 ThreadAbortException 异常




程序:

using System;
using System.Threading;
using System.Security.Permissions;

namespace TestThread
{
class Program
{
public static void Main()
{
Console.WriteLine( "Main - Begin." );

ThreadStart myThreadDelegate = new ThreadStart( DoWork );
Thread myThread = new Thread( myThreadDelegate );
myThread.Start();
Thread.Sleep( 1000 );

Console.WriteLine( "Main - Aborting my thread." );
myThread.Abort();
myThread.Join();

Console.WriteLine( "Main - End." );
}

public static void DoWork()
{
try
{
int i= -2;
while (true)
{
try
{
try
{
Console.WriteLine( string.Format( "Thread - Working now: {0}", 1 / i ) );
Thread.Sleep( 100 );
}
catch
{
Console.WriteLine( string.Format( "Thread - Working Error") );
Thread.Sleep( 3000 );
Console.WriteLine( string.Format( "Thread - Working Error processed" ) );
}
i++;
}
catch
{
Console.WriteLine( "Thread - caught Exception inner while." );
}

}
}
catch (ThreadAbortException ex)
{
Console.WriteLine( "Thread - caught ThreadAbortException outer while." );
Console.WriteLine( "Exception message: {0}", ex.Message );

Thread.Sleep( 4000 );

Console.WriteLine( "Thread - ResetAbort()" );

Thread.ResetAbort();
}

Console.WriteLine( "Thread - still alive and working." );

Console.WriteLine( "Thread - finished working." );
}

}

}
Notemper2x 3.1 ( ̄ε( ̄#)
没脾气2x 之 个人综合篇: http://notemper2x.cndev.org/
我的 panoramio 相册: http://panoramio.com/user/zhaixudong
我的 flickr相册: http://www.flickr.com/photos/notemper2x/



QQ号20250出售,售价400,000元整(5位、皇冠80级、VIP7)

相关信息:


欢迎光临本社区,您还没有登录,不能发贴子。请在 这里登录