您的位置:首页 > 编程语言 > C#

【转】C# 创建 终止线程

2007-08-07 12:31 417 查看
using System;
using System.Threading;

public class Worker
{
// This method will be called when the thread is started.
public void DoWork()
{
while (!_shouldStop)
{
Console.WriteLine("worker thread: working...");
}
Console.WriteLine("worker thread: terminating gracefully.");
}
public void RequestStop()
{
_shouldStop = true;
}
// Volatile is used as hint to the compiler that this data
// member will be accessed by multiple threads.
private volatile bool _shouldStop;
}

public class WorkerThreadExample
{
static void Main()
{
// Create the thread object. This does not start the thread.
Worker workerObject = new Worker();
Thread workerThread = new Thread(workerObject.DoWork);

// Start the worker thread.
workerThread.Start();
Console.WriteLine("main thread: Starting worker thread...");

// Loop until worker thread activates.
while (!workerThread.IsAlive);

// Put the main thread to sleep for 1 millisecond to
// allow the worker thread to do some work:
Thread.Sleep(1);

// Request that the worker thread stop itself:
workerObject.RequestStop();

// Use the Join method to block the current thread
// until the object's thread terminates.
workerThread.Join();
Console.WriteLine("main thread: Worker thread has terminated.");
}
}

示例输出

main thread: starting worker thread...
worker thread: working...
worker thread: working...
worker thread: working...
worker thread: working...
worker thread: working...
worker thread: working...
worker thread: working...
worker thread: working...
worker thread: working...
worker thread: working...
worker thread: working...
worker thread: terminating gracefully...
main thread: worker thread has terminated

请参见

任务

“线程”示例

参考

线程处理(C# 编程指南)
使用线程处理(C# 编程指南)
volatile(C# 参考)
Thread
Mutex
Monitor
Start
IsAlive
Sleep
Join
Abort

概念

C# 编程指南

其他资源

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