欢迎来到忆约科技! 手机版
编程专栏
网络探索
科技频道
社会话题
美文鉴赏

Thread.IsBackground 属性

编辑时间:2018年01月31日 14:31 作者:E小编

https://technet.microsoft.com/zh-cn/library/system.threading.thread.isbackground

https://technet.microsoft.com/en-us//library/system.threading.thread.isbackground

MSDN解释:获取或设置一个值,该值指示某个线程是否为后台线程。


下面的示例对比前台和后台线程的行为。 它将创建一个前台线程和后台线程。 前台线程前让进程一直运行,直到完成其for循环并终止。 但是,如示例输出所示,因为前台线程已完成执行,后台线程完成执行之前,已终止进程。

using System;
using System.Threading;

class Example
{
    static void Main()
    {
        BackgroundTest shortTest = new BackgroundTest(10);
        Thread foregroundThread =
            new Thread(new ThreadStart(shortTest.RunLoop));

        BackgroundTest longTest = new BackgroundTest(50);
        Thread backgroundThread =
            new Thread(new ThreadStart(longTest.RunLoop));
        // IsBackground = true 前台线程结束,同时结束后台正在运行的线程
        // IsBackground = false 前台线程结束,后台线程继续执行 
        backgroundThread.IsBackground = true;

        foregroundThread.Start();
        backgroundThread.Start();
    }
}

class BackgroundTest
{
    int maxIterations;

    public BackgroundTest(int maxIterations)
    {
        this.maxIterations = maxIterations;
    }

    public void RunLoop()
    {
        for (int i = 0; i < maxIterations; i++)
        {
            Console.WriteLine("{0} count: {1}",
                Thread.CurrentThread.IsBackground ?
                   "Background Thread" : "Foreground Thread", i);
            Thread.Sleep(250);
        }
        Console.WriteLine("{0} finished counting.",
                          Thread.CurrentThread.IsBackground ?
                          "Background Thread" : "Foreground Thread");
    }
}
// The example displays output like the following:
//    Foreground Thread count: 0
//    Background Thread count: 0
//    Background Thread count: 1
//    Foreground Thread count: 1
//    Foreground Thread count: 2
//    Background Thread count: 2
//    Foreground Thread count: 3
//    Background Thread count: 3
//    Background Thread count: 4
//    Foreground Thread count: 4
//    Foreground Thread count: 5
//    Background Thread count: 5
//    Foreground Thread count: 6
//    Background Thread count: 6
//    Background Thread count: 7
//    Foreground Thread count: 7
//    Background Thread count: 8
//    Foreground Thread count: 8
//    Foreground Thread count: 9
//    Background Thread count: 9
//    Background Thread count: 10
//    Foreground Thread count: 10
//    Background Thread count: 11
//    Foreground Thread finished counting.


二维码