1、理论两者区别:
应用程序必须运行完所有前台线程后才能退出;
对于后台线程,应用程序可以不考虑其是否已运行完毕而直接退出,所有后台线程在应用程序退出时都会自动结束。
2、案例说明
前台线程与后台线程的执行与应用程序:
(1)代码演示
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.Threading;
- namespace BackgroundAndForeground
- {
- class Program
- {
- static void Main(string[] args)
- {
- 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();
- // Console.ReadLine();
- }
- }
- ///
- /// 本类里的函数做线程的回调函数
- ///
- 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);
- }
- }
- }
(2)执行效果
图 main中不加ReadLine
图 main中加ReadLine
3、工程源代码
BackgroundAndForeground.rar
阅读(4526) | 评论(0) | 转发(0) |