欢迎光临
我们一直在努力

(七)线程–管理线程(使线程中止,暂停,挂起等)-.NET教程,算法/线程

建站超值云服务器,限时71元/月

 

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

赞(0)
版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com 特别注意:本站所有转载文章言论不代表本站观点! 本站所提供的图片等素材,版权归原作者所有,如需使用,请与原作者联系。未经允许不得转载:IDC资讯中心 » (七)线程–管理线程(使线程中止,暂停,挂起等)-.NET教程,算法/线程
分享到: 更多 (0)

相关推荐

  • 暂无文章