志在指尖
用双手敲打未来

C#前台线程和后台线程区别及代码示例讲解

由于时间片的原因,虽然所有线程在微观上是串行履行的,但在宏观上可以认为是并行履行。
线程有两种类型:前台和后台。我们可以经过线程特点IsBackground=false来指定线程的前后台特点(默认是前台线程)。
区别是:前台线程的程序,必须等所有的前台线程运行完毕后才干退出;而后台线程的程序,只要前台的线程都终止了,那么后台的线程就会自动完毕并推出程序。
用法方向:一般前台线程用于需要长时间等待的使命,比方监听客户端的恳求;后台线程一般用于处理时间较短的使命,比方处理客户端发过来的恳求信息。
前台线程:
[C#]纯文本查看
usingSystem;
usingSystem.Collections.Generic;
usingSystem.Text;
usingSystem.Threading;
namespaceDemo
{
classProgram
{
staticvoidMain(string[]args)
{
ThreadaThread=newThread(threadFunction);
Console.WriteLine(“Threadisstarting…”);
aThread.Start();
Console.WriteLine(“Applicationisterminating…”);
}
publicstaticvoidthreadFunction()
{
Console.WriteLine(“Threadissleeping…”);
Thread.Sleep(5000);
Console.WriteLine(“Threadisaborted!”);
}
}
}c#
后台线程:
[C#]纯文本查看
usingSystem;
usingSystem.Collections.Generic;
usingSystem.Text;
usingSystem.Threading;
namespaceDemo
{
classProgram
{
staticvoidMain(string[]args)
{
ThreadaThread=newThread(threadFunction);
aThread.IsBackground=true;
Console.WriteLine(“Threadisstarting…”);
aThread.Start();
Console.WriteLine(“Applicationisterminating…”);
}
publicstaticvoidthreadFunction()
{
Console.WriteLine(“Threadissleeping…”);
Thread.Sleep(5000);
Console.WriteLine(“Threadisaborted!”);
}
}
}

未经允许不得转载:IT技术网站 » C#前台线程和后台线程区别及代码示例讲解
分享到: 更多 (0)

评论 抢沙发

评论前必须登录!

 

志在指尖 用双手敲打未来

登录/注册IT技术大全

热门IT技术

C#基础入门   SQL server数据库   系统SEO学习教程   WordPress小技巧   WordPress插件   脚本与源码下载