线程调用abort()会触发ThreadAbortException异常,调试时不想触发该异常的解决方式。
1、初始化线程
1 /// <summary> 2 /// 初始化 3 /// </summary> 4 public void InitTask() 5 { 6 //构建线程,启动 7 _Thread = new Thread(new ThreadStart(() => 8 { 9 try 10 { 11 //开始循环 12 while (_isTaskStart) 13 { 14 Thread.Sleep(100); //do something 15 } 16 } 17 catch (Exception ex) 18 { 19 //TODO:记录日志 20 } 21 _drawThread = null; 22 })); 23 _drawThread.IsBackground = true; 24 _drawThread.Start(); 25 }
2、终止线程
1 /// <summary> 2 /// 释放资源 3 /// </summary> 4 protected void DisposeThread() 5 { 6 // 释放。 7 if (_drawThread != null) 8 { 9 _drawThread.Abort(); 10 while (_drawThread != null && _drawThread.IsAlive) 11 { 12 Thread.Sleep(10); 13 } 14 _drawThread = null; 15 } 16 }
触发异常:
调试阶段避免频繁触发异常解决方法:
1、异常设置=》common language中去除ThreadAbortException。两种方式
A:直接在异常界面,下角有个异常设置,取消勾选。
B:调试菜单=>窗口=>异常设置=>common language runtime exceptions=>ThreadAbortException
上面办法去除ThreadAbortException选项的勾选,调试仍然出现异常断点,则可能环境设置仍有问题,解决方式: