c# Thread类线程常用操作详解
创建线程
线程是通过扩展Thread类创建的。扩展的Thread类调用Start() 方法来开始子线程的执行。
下面的程序演示了这个概念:
classThreadCreationProgram
{
publicstaticvoidCallToChildThread()
{
Console.WriteLine("Childthreadstarts");
}
staticvoidMain(string[]args)
{
ThreadStartchildref=newThreadStart(CallToChildThread);
Console.WriteLine("InMain:CreatingtheChildthread");
ThreadchildThread=newThread(childref);
childThread.Start();
Console.ReadKey();
}
}
当上面的代码被编译和执行时,它会产生下列结果:
InMain:CreatingtheChildthread Childthreadstarts
管理线程
Thread类提供了各种管理线程的方法。
下面的实例演示了sleep() 方法的使用,用于在一个特定的时间暂停线程。
classThreadCreationProgram
{
publicstaticvoidCallToChildThread()
{
Console.WriteLine("Childthreadstarts");
//线程暂停5000毫秒
intsleepfor=5000;
Console.WriteLine("ChildThreadPausedfor{0}seconds",
sleepfor/1000);
Thread.Sleep(sleepfor);
Console.WriteLine("Childthreadresumes");
}
staticvoidMain(string[]args)
{
ThreadStartchildref=newThreadStart(CallToChildThread);
Console.WriteLine("InMain:CreatingtheChildthread");
ThreadchildThread=newThread(childref);
childThread.Start();
Console.ReadKey();
}
}
当上面的代码被编译和执行时,它会产生下列结果:
InMain:CreatingtheChildthread Childthreadstarts ChildThreadPausedfor5seconds Childthreadresumes
销毁线程
Abort() 方法用于销毁线程。
通过抛出threadabortexception在运行时中止线程。这个异常不能被捕获,如果有finally块,控制会被送至finally块。
下面的程序说明了这点:
classThreadCreationProgram
{
publicstaticvoidCallToChildThread()
{
try
{
Console.WriteLine("Childthreadstarts");
//计数到10
for(intcounter=0;counter<=10;counter++)
{
Thread.Sleep(500);
Console.WriteLine(counter);
}
Console.WriteLine("ChildThreadCompleted");
}
catch(ThreadAbortExceptione)
{
Console.WriteLine("ThreadAbortException");
}
finally
{
Console.WriteLine("Couldn'tcatchtheThreadException");
}
}
staticvoidMain(string[]args)
{
ThreadStartchildref=newThreadStart(CallToChildThread);
Console.WriteLine("InMain:CreatingtheChildthread");
ThreadchildThread=newThread(childref);
childThread.Start();
//停止主线程一段时间
Thread.Sleep(2000);
//现在中止子线程
Console.WriteLine("InMain:AbortingtheChildthread");
childThread.Abort();
Console.ReadKey();
}
}
当上面的代码被编译和执行时,它会产生下列结果:
InMain:CreatingtheChildthread Childthreadstarts 0 1 2 InMain:AbortingtheChildthread ThreadAbortException Couldn'tcatchtheThreadException
以上就是c#Thread类线程常用操作详解的详细内容,更多关于c#Thread类线程的资料请关注毛票票其它相关文章!
声明:本文内容来源于网络,版权归原作者所有,内容由互联网用户自发贡献自行上传,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任。如果您发现有涉嫌版权的内容,欢迎发送邮件至:czq8825#qq.com(发邮件时,请将#更换为@)进行举报,并提供相关证据,一经查实,本站将立刻删除涉嫌侵权内容。