(七)线程--管理线程(使线程中止,暂停,挂起等)

(一).描述
此示例演示怎样设置线程的状态(中止,暂停,挂起等)
(二).代码
using System;
using System.Threading;

namespace 管理线程_使线程中止_暂停_挂起等_
{
//委托声明(函数签名)
delegate string MyMethodDelegate();
class MyClass
{
public static void Method1()
{
//thread1.Abort();一句中的 Abort会引发异常System.Threading.ThreadAbortException,其异常作用,下面会讲解
try
{
int i;
for(i=0;i<10;i++)
{
Console.WriteLine("Method1 at :" + i.ToString());
DelayTime(1); //延长时间(模拟执行任务)
}
}
catch(System.Threading.ThreadAbortException)
{
//注意一点,线程跳出此语句块后才终止。
//这里可以写释放此进程占用的资源代码,或者其它一些操作,比如: 在进程结束前将重要数据写回数据库中
Console.WriteLine("进程1马上将被强制杀死!");
Thread.ResetAbort(); //取消Abort()操作,我在这里加这句没用,反而出现异常了,读者如果知道,请告诉我怎样写才对
}
}
public static void Method2()
{
int i;
for(i=0;i<10;i++)
{
Console.WriteLine("Method2 at :" + i.ToString());
DelayTime(1); //延长时间,模拟执行任务
}
}

private static void DelayTime(int n)
{
DateTime startTime = DateTime.Now;
while(startTime.AddSeconds(n) > DateTime.Now)
{
//延长时间,模拟实际中的进程
}
}

[STAThread]
static void Main(string[] args)
{
Thread thread1 = new Thread(new ThreadStart(Method1));
Thread thread2 = new Thread(new ThreadStart(Method2));
thread1.Start();
thread2.Start();
thread1.Abort(); //将线程强制终止(杀死)

//thread1.Join的作用是无限制等待thread1终止后,才执行下面的语句,起到与主线程同步的作用.
//原因是: thread1最终是被终止的,但是thread1一个独立的线程,它并不会马上被终止。
//什么时候用:就拿这里来举例吧,当thread1占用着一个资源,当thread1终止后,
//thread2线程马上也要用此资源,这就要求等待thread1彻底终止并释放后占用资源后,才能接着执行下一句,
//否则线程thread2会找不到此资源,甚至会发生异常错误! 为了安全起见,一般是要在Abort()方法后面紧跟一个Join()方法的.

//thread1.Suspend();//此方法将线程无限制时间的挂起,相当于无限制时间的暂停线程
//thread1.Resume(); //将正在挂起的进程继续执行

//Thread.Sleep(1000);//暂停线程1秒钟,以毫秒为单位暂停.

//Thread.ResetAbort(); //取消Abort()操作
//thread1.Interrupt(); //中止线程现在处的状态。如果线程由运行转到休眠,执行此句后,会使线程重新返回到运行状态

Console.Read();
}
}
}

本示例代码已经测试,能够正常运行!

(三).示例下载
http://www.cnblogs.com/Files/ChengKing/ThreadExample.rar

Published At
Categories with Web编程
Tagged with
comments powered by Disqus