【C#】39. 前台线程与后台线程

本文通过实例代码展示了前台线程与后台线程的主要区别:进程会等待前台线程结束后才能结束,而不会理会后台线程的执行状况。显示创建的线程默认为前台线程,可通过设置IsBackground属性变为后台线程。

这篇文章主要介绍一下前台线程后后台线程的区别:进程会等待前台线程结束后才能结束,而不会理会后台线程的执行状况。显示创建的线程默认情况下都是前台线程,除非手动设置 IsBackground = True。


using System;
using System.Threading;

namespace Chapter1.Recipe7
{
class Program
{
static void Main(string[] args)
{
var sampleForeground = new ThreadSample(10);
var sampleBackground = new ThreadSample(20);

var threadOne = new Thread(sampleForeground.CountNumbers);
threadOne.Name = "ForegroundThread";
var threadTwo = new Thread(sampleBackground.CountNumbers);
threadTwo.Name = "BackgroundThread";
threadTwo.IsBackground = true; //显示创建的线程都是前台线程,除非像这样将其设置为后台线程。

threadOne.Start();
threadTwo.Start();
}

class ThreadSample
{
private readonly int _iterations;

public ThreadSample(int iterations)
{
_iterations = iterations;
}
public void CountNumbers()
{
for (int i = 0; i < _iterations; i++)
{
Thread.Sleep(TimeSpan.FromSeconds(0.5));
Console.WriteLine("{0} prints {1}", Thread.CurrentThread.Name, i);
}
}
}
}
}



前台线程ForgroundThread会在打印10次后结束(stopped状态),从而结束整个main函数。而后台线程BackgroundThread只能跟着结束,虽然他只打印了10次而不是20次。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值