现在的位置: 首页 > 综合 > 正文

.NET中的后台线程–IsBackground属性

2017年11月25日 ⁄ 综合 ⁄ 共 1641字 ⁄ 字号 评论关闭

情境: 最近用winform做一个小程序,主要是用来执行一些sql语句,无奈数据量太大,执行一次要二十分钟左右,执行期间界面根本不能再进行其它操作,就连最小化窗口都不行,一动就跟死机差不多了.

因此到网上搜了一下,找到.net后台线程的概念.(高手请绕道!)

前台线程和后台线程之间的选择
.NET Framework 中的所有线程都被指定为前台线程或后台线程。这两种线程唯一的区别是 — 后台线程不会阻止进程终止。在属于一个进程的所有前台线程终止之后,公共语言运行库 (CLR) 就会结束进程,从而终止仍在运行的任何后台线程。

在默认情况下,通过创建并启动新的 Thread 对象生成的所有线程都是前台线程,而从非托管代码进入托管执行环境中的所有线程都标记为后台线程。然而,通过修改 Thread.IsBackground 属性,可以指定一个线程是前台线程还是后台线程。通过将 Thread.IsBackground 设置为 true,可以将一个线程指定为后台线程;通过将 Thread.IsBackground 设置为 false,可以将一个线程指定为前台线程。

示例:
下面的代码示例对比了前台线程与后台线程的行为。创建一个前台线程和一个后台线程。前台线程使进程保持运行,直到它完成它的 while 循环。前台线程完成后,进程在后台线程完成它的 while 循环之前终止。

using System;
using System.Threading;

class Test
{
    
static void Main()
    
{
        BackgroundTest shortTest 
= new BackgroundTest(10);
        Thread foregroundThread 
= 
            
new Thread(new ThreadStart(shortTest.RunLoop));
        foregroundThread.Name 
= "ForegroundThread";

        BackgroundTest longTest 
= new BackgroundTest(50);
        Thread backgroundThread 
= 
            
new Thread(new ThreadStart(longTest.RunLoop));
        backgroundThread.Name 
= "BackgroundThread";
        backgroundThread.IsBackground 
= true;

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

}


class BackgroundTest
{
    
int maxIterations;

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


    
public void RunLoop()
    
{
        String threadName 
= Thread.CurrentThread.Name;
        
        
for(int i = 0; i < maxIterations; i++)
        
{
            Console.WriteLine(
"{0} count: {1}"
                threadName, i.ToString());
            Thread.Sleep(
250);
        }

        Console.WriteLine(
"{0} finished counting.", threadName);
    }

}

【上篇】
【下篇】

抱歉!评论已关闭.