对C#中Thread.IsBackground属性的理解
2015-12-02 11:15:51 访问(2533) 赞(0) 踩(0)
原文地址:http://blog.csdn.net/luckeryin/article/details/5649144
C#中,Thread类有一个IsBackground 的属性.MSDN上对它的解释是:获取或设置一个值,该值指示某个线程是否为后台线程。个人感觉这样的解释等于没有解释.
.Net中的线程,可以分为后台线程和前台线程。后台线程与前台线程并没有本质的区别,它们之间唯一的区别就是:后台线程不会防止应用程序的进程被终止掉。呵呵,这句话读出来好像并不那么好懂.其实,说白了就是当前台线程都结束了的时候,整个程序也就结束了,即使还有后台线程正在运行,此时,所有剩余的后台线程都会被停止且不会完成.但是,只要还有一个前台线程没有结束,那么它将阻止程序结束.这就是为什么有些设计不够完美的WinForm程序,在某种特定的情况下,即使所有的窗口都关闭了,但是在任务管理器的管理列表里仍然可以找到该程序的进程,仍然在消耗着CPU和内存资源.因此,在WinForm程序中,关闭所有窗口前,应该停止所有前台线程,千万不要遗忘了某个前台线程.应用程序进程的存亡由前台线程决定而于后台线程无关.这就是它们的区别.
知道了前后台线程的区别,就应该知道如何声明IsBackgroud属性的值了.
值得说明的一点是:改变线程从前台到后台不会以任何方式改变它在CPU协调程序中的优先级和状态。因为前台后线程与程序进程的优先级无关.
结束前摘录MSDN上一段示例码,以帮助大家便好的理解这一区别:
下面的代码示例对比了前台线程与后台线程的行为。创建一个前台线程和一个后台线程。前台线程使进程保持运行,直到它完成它的 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);
}
}
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using System.IO;
namespace ConsoleApplication1
{
public class Program
{
static void Main()
{
BackgroundTest shortTest = new BackgroundTest(10,1);
Thread foregroundThread =
new Thread(new ThreadStart(shortTest.RunLoop));
foregroundThread.Name = "ForegroundThread";
BackgroundTest longTest = new BackgroundTest(50,2);
Thread backgroundThread =
new Thread(new ThreadStart(longTest.RunLoop));
backgroundThread.Name = "BackgroundThread";
backgroundThread.IsBackground = true;
foregroundThread.Start();
backgroundThread.Start();
string str = "main end";
while (Util.isWrite != 0)
{
continue;
}
Util.isWrite = 10;
Util.WriteFile(@"d:\tmp\thread.txt", str);
Util.isWrite = 0;
Console.WriteLine(str);
}
}
public class BackgroundTest
{
int maxIterations;
int tId = 0;
public BackgroundTest(int _maxIterations, int _tId)
{
this.maxIterations = _maxIterations;
tId = _tId;
}
public void RunLoop()
{
string str = null;
String threadName = Thread.CurrentThread.Name;
for (int i = 0; i < maxIterations; i++)
{
str = string.Format("{0} count: {1}",
threadName, i.ToString());
while (Util.isWrite != 0)
{
continue;
}
Util.isWrite = this.tId;
Util.WriteFile(@"d:\tmp\thread.txt", str);
Util.isWrite = 0;
Console.WriteLine(str);
Thread.Sleep(250);
}
str = string.Format("{0} finished counting.", threadName);
while (Util.isWrite != 0)
{
continue;
}
Util.isWrite = this.tId;
Util.WriteFile(@"d:\tmp\thread.txt", str);
Util.isWrite = 0;
Console.WriteLine(str);
}
}
public class Util
{
public static int isWrite = 0;
#region 写入文件
/// <summary>
/// 写入文件
/// </summary>
/// <param name="fileName"></param>
/// <param name="textValue"></param>
public static void WriteFile(string fileName, string textValue)
{
WriteFile(fileName, textValue + System.Environment.NewLine, null, true, true);
}
/// <summary>
/// 写入文件
/// </summary>
/// <param name="fileName"></param>
/// <param name="textValue"></param>
/// <param name="textEncoding"></param>
public static void WriteFile(string fileName, string textValue, System.Text.Encoding textEncoding)
{
WriteFile(fileName, textValue, textEncoding, true, true);
}
/// <summary>
/// 写入文件
/// </summary>
/// <param name="fileName"></param>
/// <param name="textValue"></param>
/// <param name="textEncoding"></param>
/// <param name="IsOverwrite"></param>
public static void WriteFile(string fileName, string textValue, System.Text.Encoding textEncoding, bool IsOverwrite)
{
WriteFile(fileName, textValue, textEncoding, IsOverwrite, true);
}
/// <summary>
/// 写入文件
/// </summary>
/// <param name="fileName"></param>
/// <param name="textValue"></param>
/// <param name="textEncoding"></param>
/// <param name="IsOverwrite"></param>
/// <param name="IsAppend"></param>
public static void WriteFile
(
string fileName,
string textValue,
System.Text.Encoding textEncoding,
bool IsOverwrite,
bool IsAppend
)
{
if (fileName == null || fileName.Length == 0)
return;
FileInfo info = new FileInfo(fileName);
if (info.Exists)
{
// 文件存在,且不覆盖 //
if (!IsOverwrite)
return;
// 如果不是追加 //
if (!IsAppend)
File.Delete(info.FullName);
}
else
{
// 创建目录 //
if (!info.Directory.Exists)
{
Directory.CreateDirectory(info.Directory.FullName);
}
}
FileStream fs = null;
StreamWriter m_streamWriter = null;
try
{
//创建一个文件流,用以写入或者创建一个StreamWriter
fs = new FileStream(info.FullName, FileMode.OpenOrCreate, FileAccess.Write);
if (textEncoding == null)
{
m_streamWriter = new StreamWriter(fs);
}
else
{
m_streamWriter = new StreamWriter(fs, textEncoding);
}
m_streamWriter.Flush();
// 使用StreamWriter来往文件中写入内容
if (IsAppend)
m_streamWriter.BaseStream.Seek(0, SeekOrigin.End);
m_streamWriter.Write(textValue);
m_streamWriter.Flush();
}
catch (Exception err)
{
throw err;
}
finally
{
if (m_streamWriter != null)
{
m_streamWriter.Flush();
m_streamWriter.Close();
}
if (fs != null)
{
fs.Close();
}
m_streamWriter = null;
fs = null;
}
}
#endregion 写入文件
}
}
输出结果:
main end
BackgroundThread count: 0
ForegroundThread count: 0
BackgroundThread count: 1
ForegroundThread count: 1
BackgroundThread count: 2
ForegroundThread count: 2
BackgroundThread count: 3
ForegroundThread count: 3
BackgroundThread count: 4
ForegroundThread count: 4
BackgroundThread count: 5
ForegroundThread count: 5
BackgroundThread count: 6
ForegroundThread count: 6
BackgroundThread count: 7
ForegroundThread count: 7
BackgroundThread count: 8
ForegroundThread count: 8
BackgroundThread count: 9
ForegroundThread count: 9
BackgroundThread count: 10
ForegroundThread finished counting.
说明:
前台进程ForegroundThread运行完后,BackgroundThread就停止运行。
标签:
线程 


C# 


Thread.IsBackground 


上一条:
下一条:
相关评论
发表评论