当调用thread.abort()方法时,在msdn上讲到会产生System.Threading.ThreadAbortException,但是为什么,
我的代码是这样的public class FlashThread
{
Thread _stateRefresh;
public FlashThread()
{
_stateRefresh = new Thread(new ThreadStart(StateRefresh));
_stateRefresh.IsBackground = true;
_stateRefresh.SetApartmentState(ApartmentState.STA);
_stateRefresh.Start();
}
public void Close()
{
_stateRefresh.Abort();
}
private void StateRefresh()
{
FormFlash flash = new FormFlash();
flash.ShowDialog();
} }
}我没有try-catch语句,它在大部分机器上运行没有报System.Threading.ThreadAbortException: Thread was being aborted.但是在有的机器上它偶尔会出现
System.Threading.ThreadAbortException: Thread was being aborted.
at System.Windows.Forms.UnsafeNativeMethods.GetWindowPlacement(HandleRef hWnd, WINDOWPLACEMENT& placement)
at System.Windows.Forms.Form.UpdateWindowState()
at System.Windows.Forms.Form.WndProc(Message& m)
at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
at System.Windows.Forms.NativeWindow.Callback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
是不是抛出这个异常是有条件的!
我的代码是这样的public class FlashThread
{
Thread _stateRefresh;
public FlashThread()
{
_stateRefresh = new Thread(new ThreadStart(StateRefresh));
_stateRefresh.IsBackground = true;
_stateRefresh.SetApartmentState(ApartmentState.STA);
_stateRefresh.Start();
}
public void Close()
{
_stateRefresh.Abort();
}
private void StateRefresh()
{
FormFlash flash = new FormFlash();
flash.ShowDialog();
} }
}我没有try-catch语句,它在大部分机器上运行没有报System.Threading.ThreadAbortException: Thread was being aborted.但是在有的机器上它偶尔会出现
System.Threading.ThreadAbortException: Thread was being aborted.
at System.Windows.Forms.UnsafeNativeMethods.GetWindowPlacement(HandleRef hWnd, WINDOWPLACEMENT& placement)
at System.Windows.Forms.Form.UpdateWindowState()
at System.Windows.Forms.Form.WndProc(Message& m)
at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
at System.Windows.Forms.NativeWindow.Callback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
是不是抛出这个异常是有条件的!
Response.Redirect和Response.End都会抛出这个异常。
想想一个方法可以做到终止后面的代码运行就可以明白了。
其内部实现肯定是这样的:
System.Threading.Thread.CurrentThread.Abort();
这个异常即常你catch,他也会往上继续走下去。
你在记录日志的时候若想忽略它可以这么做:
try
{
}
catch(System.Threading.ThreadAbortException)
{
...不进行任何操作
}
catch(System.Exception)
{
....记录日志
}
想了几天也没有想出来,急死了!
另外,是不是产生的System.Threading.ThreadAbortException,被.NET内部给处理了,我记得好像在c#里,如果产生的异常,不try-catch掉,就程序很有可能是会弹出这种对话框,但是为什么我没用try-catch,有大多数机器没有出现,而有少数机器弹出的这个对话框。