方法执行超时则终止方法思路

 

今天想一个方法的超时则强行终止该方法思路,处于实验阶段,尚未正式使用。总体思路如下:

1,把需要执行的方法放在一个线程中A,执行。

2,把线程A作为参数传入线程B中,在B中执行一个循环,如果超时则强行终止该线程。

 

代码如下:

 

详细代码
public   interface  IExcecMehtod
{
     
void  ExecMethodWithLongTime();
}
public   class  MethodExecHelper
{
     
#region  全局变量
     IExcecMehtod methodHost 
=   null ;
     
public  IExcecMehtod MethodHost
     {
         
get  {  return  methodHost; }
         
set  { methodHost  =  value; }
     }
     
private   int  timeOut;
     
///   <summary>
     
///  方法执行超时时间(单位:秒)
     
///   </summary>
      public   int  TimeOut
     {
         
get
         {
             
return  timeOut;
         }
         
set
         {
             timeOut 
=  value;
         }
     }
     
#endregion
     
#region  构造函数
     
public  MethodExecHelper(IExcecMehtod methodHost,  int  timeOut)
     {
         
this .methodHost  =  methodHost;
         
this .timeOut  =  timeOut;
     }
     
public  MethodExecHelper(IExcecMehtod methodHost)
         : 
this (methodHost,  5 )
     {
     }
     
#endregion
     
#region  对外方法
     
public   void  Run()
     {
         Thread execThread 
=   new  Thread( new  ThreadStart(WaitMethod));
         execThread.Start();
         Thread abortThread 
=   new  Thread( new  ParameterizedThreadStart(AbortMehtod));
         abortThread.Start(execThread);
     }
     
#endregion
     
#region  私有方法
     
void  AbortMehtod( object  state)
     {
         
bool  flag  =   false ;
         DateTime beginTime 
=  DateTime.Now;
         
while  ( ! flag)
         {
             DateTime currentTime 
=  DateTime.Now;
             
if  ((currentTime  -  beginTime).Seconds  >  TimeOut)
             {
                 Thread thread 
=  state  as  Thread;
                 
if  (thread  !=   null )
                 {
                     
if  (thread.IsAlive)
                     {
                         thread.Abort();
                         Debug.WriteLine(
" 线程强行终止 " );
                     }
                 }
                 flag 
=   true ;
             }
             Thread.Sleep(
1000 );
         }
     }
     
void  WaitMethod()
     {
         MethodHost.ExecMethodWithLongTime();
         Debug.WriteLine(
" 线程执行完成 " );
     }
     
#endregion
}

 

 

转载于:https://www.cnblogs.com/wangn/archive/2009/12/02/1615078.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值