C#如何控制方法的执行时间,超时则强制退出方法执行

有时候我们需要控制方法的执行时间,如果超时则强制退出。

要控制执行时间,我们必须使用异步模式,在另外一个线程中执行方法,如果超时,则抛出异常终止线程执行。

如下使用异步执行委托的方式实现,使用WaitHandle的WaitOne方法来计算时间超时:

class Program{
    static void Main(string[] args)    {
        //try the five second method with a 6 second timeout
        CallWithTimeout(FiveSecondMethod, 6000);
        //try the five second method with a 4 second timeout
        //this will throw a timeout exception
        CallWithTimeout(FiveSecondMethod, 4000);
    }
    static void FiveSecondMethod()    {
        Thread.Sleep(5000);
    }
    static void CallWithTimeout(Action action, int timeoutMilliseconds)    {
        Thread threadToKill = null;
        Action wrappedAction = () =>
        {
            threadToKill = Thread.CurrentThread;
            action();
        };
        IAsyncResult result = wrappedAction.BeginInvoke(null, null);
        if (result.AsyncWaitHandle.WaitOne(timeoutMilliseconds))        {
            wrappedAction.EndInvoke(result);
        }
        else
        {
            threadToKill.Abort();
            throw new TimeoutException();
        }
    }}


  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值