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

情境: 最近用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);
    }

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值