Chinaunix首页 | 论坛 | 博客
  • 博客访问: 12300688
  • 博文数量: 1293
  • 博客积分: 13501
  • 博客等级: 上将
  • 技术积分: 17974
  • 用 户 组: 普通用户
  • 注册时间: 2011-03-08 18:11
文章分类

全部博文(1293)

文章存档

2019年(1)

2018年(1)

2016年(118)

2015年(257)

2014年(128)

2013年(222)

2012年(229)

2011年(337)

分类: 嵌入式

2012-08-27 14:31:55

1、理论两者区别:

应用程序必须运行完所有前台线程后才能退出;

对于后台线程,应用程序可以不考虑其是否已运行完毕而直接退出,所有后台线程在应用程序退出时都会自动结束。

2、案例说明

前台线程与后台线程的执行与应用程序:

(1)代码演示


点击(此处)折叠或打开

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Threading;

  6. namespace BackgroundAndForeground
  7. {
  8.     class Program
  9.     {
  10.         static void Main(string[] args)
  11.         {
  12.             BackgroundTest shortTest = new BackgroundTest(10);
  13.             Thread foregroundThread =
  14.                 new Thread(new ThreadStart(shortTest.RunLoop));
  15.             foregroundThread.Name = "ForegroundThread";


  16.             /* 这个将函数封装到一个类的方法较少用,试试 */
  17.             BackgroundTest longTest = new BackgroundTest(50);

  18.             Thread backgroundThread =
  19.                 new Thread(new ThreadStart(longTest.RunLoop));
  20.             backgroundThread.Name = "BackgroundThread";
  21.             backgroundThread.IsBackground = true; /* 后台线程的生成 */
  22.  

  23.             foregroundThread.Start();
  24.             backgroundThread.Start();

  25. // Console.ReadLine();
  26.         }
  27.     }

  28.     ///
  29.     /// 本类里的函数做线程的回调函数
  30.     ///
  31.     class BackgroundTest
  32.     {
  33.         int maxIterations;

  34.         public BackgroundTest(int maxIterations)
  35.         {
  36.             this.maxIterations = maxIterations;
  37.         }

  38.         /* 根据传进来的时间执行循环次数 */
  39.         public void RunLoop()
  40.         {
  41.             /* 注意获取线程名字的方法 */
  42.             String threadName = Thread.CurrentThread.Name;

  43.             for (int i = 0; i < maxIterations; i++)
  44.             {
  45.                 Console.WriteLine("{0} count: {1}",threadName, i.ToString());
  46.                 Thread.Sleep(250);
  47.             }

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

  51. }

(2)执行效果

image

图 main中不加ReadLine

image

图 main中加ReadLine

 

3、工程源代码

 BackgroundAndForeground.rar   

阅读(4423) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~