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

(一).描述 此示例演示怎样设置线程的状态(中止,暂停,挂起等) (二).代码 using System; using System.Threading; namespace 管理线程_使线程中止_暂停_挂起等_ { //委托声明(函数签名) delegate string MyMethodDelegate(); class MyClass { public static void Method1
<script src="/plus/ad_js.php?aid=5"></script>

(一).描述
   此示例演示怎样设置线程的状态(中止,暂停,挂起等)
(二).代码
   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();
  }
 }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值