|
(一).描述 此示例演示怎样设置线程的状态(中止,暂停,挂起等) (二).代码 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("Method [1] [2] [3] 下一页
|