开讲啦 王潮歌,铭记我们的爱情,王佳禾
在使用线程时,如果线程还未结束直接退出线程很有可能会导致数据丢失。
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();
如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复
Blazor server side 自家的一些开源的, 实用型项目的进度之 CEF客户端
.NET IoC模式依赖反转(DIP)、控制反转(Ioc)、依赖注入(DI)
vue+.netcore可支持业务代码扩展的开发框架 VOL.Vue 2.0版本发布
网友评论