您的位置:首页 > 其它

创建和终止线程的好方法

2009-12-30 11:32 471 查看
参见MSDN:http://msdn.microsoft.com/zh-cn/library/7a2f3ay4.aspx

使用一个标示位来判断线程何时终止,而不是使用Abort(强行终止线程,即使线程尚未完成任务)方法。

实例代码如下:

using System;
using System.Collections.Generic;
using System.Threading;

public class MyClass
{
public static void Main()
{
Console.WriteLine("Main thread is start");
ThreadTest threadTest = new ThreadTest();
Thread childThread = new Thread(threadTest.Work);
childThread.Start();
for(int i=0;i<10000;i++)
{
if(i%50 == 0)
{
Console.WriteLine("Main thread is running");
}
}
threadTest.StopThread();
childThread.Join();
Console.WriteLine("Main thread is stop");

Console.Read();
}
}

public class ThreadTest
{
private volatile bool  _threadStop;

/// <summary>
/// 执行内容
/// </summary>
public void Work()
{
Console.WriteLine("Child thread is start");
while(_threadStop == false)
{
Console.WriteLine("Child thread is running");
}
Console.WriteLine("Child thread is stop");
}

/// <summary>
/// 停止线程
/// </summary>
public void StopThread()
{
_threadStop = true;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: