C# 前台线程与后台线程
2016-06-16 10:24
453 查看
由于时间片的原因,虽然所有线程在微观上是串行执行的,但在宏观上可以认为是并行执行。
线程有两种类型:前台和后台。我们可以通过线程属性IsBackground=false来指定线程的前后台属性(默认是前台线程)。
区别是:前台线程的程序,必须等所有的前台线程运行完毕后才能退出;而后台线程的程序,只要前台的线程都终止了,那么后台的线程就会自动结束并推出程序。
用法方向:一般前台线程用于需要长时间等待的任务,比如监听客户端的请求;后台线程一般用于处理时间较短的任务,比如处理客户端发过来的请求信息。
【前台线程】
[csharp] view
plain copy
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
namespace Demo
{
class Program
{
static void Main(string[] args)
{
Thread aThread = new Thread(threadFunction);
Console.WriteLine("Thread is starting...");
aThread.Start();
Console.WriteLine("Application is terminating...");
}
public static void threadFunction()
{
Console.WriteLine("Thread is sleeping...");
Thread.Sleep(5000);
Console.WriteLine("Thread is aborted!");
}
}
}
【后台线程】
[csharp] view
plain copy
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
namespace Demo
{
class Program
{
static void Main(string[] args)
{
Thread aThread = new Thread(threadFunction);
aThread.IsBackground = true;
Console.WriteLine("Thread is starting...");
aThread.Start();
Console.WriteLine("Application is terminating...");
}
public static void threadFunction()
{
Console.WriteLine("Thread is sleeping...");
Thread.Sleep(5000);
Console.WriteLine("Thread is aborted!");
}
}
}
线程有两种类型:前台和后台。我们可以通过线程属性IsBackground=false来指定线程的前后台属性(默认是前台线程)。
区别是:前台线程的程序,必须等所有的前台线程运行完毕后才能退出;而后台线程的程序,只要前台的线程都终止了,那么后台的线程就会自动结束并推出程序。
用法方向:一般前台线程用于需要长时间等待的任务,比如监听客户端的请求;后台线程一般用于处理时间较短的任务,比如处理客户端发过来的请求信息。
【前台线程】
[csharp] view
plain copy
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
namespace Demo
{
class Program
{
static void Main(string[] args)
{
Thread aThread = new Thread(threadFunction);
Console.WriteLine("Thread is starting...");
aThread.Start();
Console.WriteLine("Application is terminating...");
}
public static void threadFunction()
{
Console.WriteLine("Thread is sleeping...");
Thread.Sleep(5000);
Console.WriteLine("Thread is aborted!");
}
}
}
【后台线程】
[csharp] view
plain copy
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
namespace Demo
{
class Program
{
static void Main(string[] args)
{
Thread aThread = new Thread(threadFunction);
aThread.IsBackground = true;
Console.WriteLine("Thread is starting...");
aThread.Start();
Console.WriteLine("Application is terminating...");
}
public static void threadFunction()
{
Console.WriteLine("Thread is sleeping...");
Thread.Sleep(5000);
Console.WriteLine("Thread is aborted!");
}
}
}
相关文章推荐
- C#算法函数:获取一个字符串中的最大长度的数字
- C#:绘图问题
- C# 第三方DLL,可以实现PDF转图片,支持32位系统、64位系统
- C#算法之大牛生小牛的问题高效解决方法
- c# 回调委托
- C#中调用abobe reader打开PDF文件的方法
- C#用递归算法实现:一列数的规则如下: 1、1、2、3、5、8、13、21、34,求第30位数是多少
- C# ?、?? 问号和2个问号的用法(类型?、对象?)
- C#游戏框架uFrame
- C#递归算法之快速排序
- 唤起你对c#曾经的记忆
- Excel在C#中的导入导出,并对值进行简单修改
- C# 发送邮件中包含图片
- c#书
- 【笔记】C#实现快捷键(系统热键)响应的方法
- VS2015中C#版本6.0的新特性 你需要知道
- C# 动态获取、修改、更新配置文件 实现思路
- QQlite 插件开发总结
- c#3.0新特性
- 常用的日期格式