当前位置: 移动技术网 > IT编程>开发语言>.net > 为什么不能用Abort退出线程

为什么不能用Abort退出线程

2018年12月13日  | 移动技术网IT编程  | 我要评论

开讲啦 王潮歌,铭记我们的爱情,王佳禾

 

在使用线程时,如果线程还未结束直接退出线程很有可能会导致数据丢失。

class threadabort
    {
        static void main(string[] args)
        {
            writemessage("主线程开始工作", consolecolor.white, consolecolor.white);
            thread th = new thread(new threadstart(testtry));
            th.start();
            thread.sleep(500);//500毫秒后结束线程
            th.abort();
            th.join();
            writemessage("主线程结束工作" + th.threadstate.tostring(), consolecolor.white, consolecolor.white);

            console.readkey();
        }

        private static void testtry()
        {
            try
            {
                for (int i = 0; i < 10; i++)
                {
                    writemessage("线程正在工作中"+i.tostring(), consolecolor.green, consolecolor.white);
                    thread.sleep(100);
                }
            }
            catch (threadabortexception ex)
            {
                writemessage("线程错误信息:" + ex.message, consolecolor.red, consolecolor.white);
            }
            finally
            {
                writemessage("线程退出。。", consolecolor.blue, consolecolor.white);
            }

            //如果线程未结束,直接abort线程,下面语句将不会被执行。
            writemessage("线程结束工作.", consolecolor.yellow, consolecolor.white);
        }

        public static void writemessage(string message, consolecolor writecolor, consolecolor backcolor)
        {
            console.foregroundcolor = writecolor;
            console.writeline(message);
            //console.backgroundcolor = backcolor;
        }
    }

  

thread.sleep(500);//500毫秒后结束线程
th.abort();

在线程启动500毫秒后,关闭线程

 writemessage("线程结束工作.", consolecolor.yellow, consolecolor.white);

将不会被执行

 

如果注释//th.abort();

 

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网