您的位置:首页 > 其它

前台线程(Foreground Threads)和后台线程(Background Threads)

2010-07-13 08:04 302 查看
不要将前台线程
(Foreground Threads)
和后台线程
(Background
Threads)

指和常说的主线程
(
Primary Thread)和工作者线程
(Worker
Thread)
混淆。

它们的定义如下
:

前台线程
(Foreground Threads):
 前台线程可以阻止程序退出。除非所有前台线程都结束,否则
CLR不会关闭程序。

后台线程
(Background Threads)


有时候也叫
Daemon
Thread
。他被
CLR
认为是不重要的执行路径,可以在任何时候舍弃。因此当所有的前台线程结束,即使还有后台线程在执行,
CLR
也会关闭程序。

使用
Thread
类启动一个线程默认就是前台线程
(Foreground Threads)
,但是可以通过给
IsBackground
赋值将线程转变为后台线程。

例如
:

public
class
Printer

{

public
void
PrintNumbers()

{

//
Display Thread info.

Console
.WriteLine("-> {0} is executing PrintNumbers()"
,

Thread
.CurrentThread.Name);

//
Print out numbers.

Console
.Write("Your numbers: "
);

for
(int
i = 0; i < 10; i++)

{

Console
.Write("{0}, "
, i);

Thread
.Sleep(2000);

}

Console
.WriteLine();

}

}

static
void
Main(string
[]
args)

{

Console
.WriteLine("***** Background Threads *****\n"
);

Printer
p = new
Printer
();

Thread
bgroundThread =

new
Thread
(new
ThreadStart
(p.PrintNumbers));

// This
is now a background thread.

bgroundThread.IsBackground = true
;

bgroundThread.Start();

}

另外从
ThreadPool
里面去的的线程默认是后台线程
(Background Threads)

例如
:

static
void
Main(string
[]
args)

{

Console
.WriteLine("***** Fun with the CLR Thread Pool *****\n"
);

Console
.WriteLine("Main thread started. ThreadID = {0}"
,

Thread
.CurrentThread.ManagedThreadId);

Printer p = new
Printer();

WaitCallback
workItem = new
WaitCallback
(PrintTheNumbers);

// Queue
the method ten times.

for
(int
i = 0; i < 10; i++)

{

ThreadPool
.QueueUserWorkItem(workItem,
p);

}

Console
.WriteLine("All tasks queued"
);

Console
.ReadLine();

}

static
void
PrintTheNumbers(object
state)

{

Printer task = (Printer)state;

task.PrintNumbers();

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: