我自己写的

        /// <summary>
/// 函数运行超时则终止执行(超时则返回true,否则返回false)
/// </summary>
/// <typeparam name="T">参数类型</typeparam>
/// <param name="action">要被执行的函数</param>
/// <param name="p">函数需要的一个参数</param>
/// <param name="timeoutMilliseconds">超时时间(毫秒)</param>
/// <returns>超时则返回true,否则返回false</returns>
void CallWithTimeout<T>(Action<T> action, T p, int timeoutMilliseconds)
{
Thread threadToKill = null;
Action wrappedAction = () =>
{
threadToKill = Thread.CurrentThread;
action(p);
}; IAsyncResult result = wrappedAction.BeginInvoke(null, null);
if (result.AsyncWaitHandle.WaitOne(timeoutMilliseconds))
{
wrappedAction.EndInvoke(result);
}
else
{
threadToKill.Abort();
throw new TimeoutException();
}
} //例子: CallWithTimeout<paramDj>(myFun,new paramDj() { dr = dr, kjh = kjh, maxQi = maxQi, minQi = minQi },);

网络上参考的

在某些情况下(例如通过网络访问数据),常常不希望程序卡住而占用太多时间以至于造成界面假死。

在这时、我们可以通过Thread、Thread + Invoke(UI)或者是 delegate.BeginInvoke 来避免界面假死,

但是这样做时,某些代码或者是某个方法的执行超时的时间还是无法操控的。
那么我们又是否有一种比较通用的方法、来设定某一个方法的执行超时的时间,让该其一旦超过指定时间则跳出指定方法、进而继续向下执行呢?

答案当然是肯定的。

delegate.BeginInvoke可以实现代码代码的异步执行,在这种情况下,只要让程序可以等待一个Timespan,如果在Timespan到达之前方法内的代码还没有执行完毕、说明该方法执行超时了。

那么关键的就是“等待一个Timespan”,而恰好.NET 里提供了一些类和方法来实现该功能。我这里选用的是ManualResetEvent.WaitOne(timespan, false);其返回值代码其是否在特定时间内收到信号,而我们恰好可以利用这个布尔值 外加一个标记变量 来判断一个方法是否执行超时。

相关的实现代码如下:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading; namespace Common
{
public delegate void DoHandler(); public class Timeout
{
private ManualResetEvent mTimeoutObject;
//标记变量
private bool mBoTimeout; public DoHandler Do; public Timeout()
{
// 初始状态为 停止
this.mTimeoutObject = new ManualResetEvent(true);
}
///<summary>
/// 指定超时时间 异步执行某个方法
///</summary>
///<returns>执行 是否超时</returns>
public bool DoWithTimeout(TimeSpan timeSpan)
{
if (this.Do == null)
{
return false;
}
this.mTimeoutObject.Reset();
this.mBoTimeout = true; //标记
this.Do.BeginInvoke(DoAsyncCallBack, null);
// 等待 信号Set
if (!this.mTimeoutObject.WaitOne(timeSpan, false))
{
this.mBoTimeout = true;
}
return this.mBoTimeout;
}
///<summary>
/// 异步委托 回调函数
///</summary>
///<param name="result"></param>
private void DoAsyncCallBack(IAsyncResult result)
{
try
{
this.Do.EndInvoke(result);
// 指示方法的执行未超时
this.mBoTimeout = false;
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
this.mBoTimeout = true;
}
finally
{
this.mTimeoutObject.Set();
}
}
}
}

测试代码如下:

class Program
{
privatestatic Stopwatch watch;
privatestatic System.Threading.Timer timer; [STAThread]
staticvoid Main(string[] args)
{
watch =new Stopwatch();
Timeout timeout =new Timeout();
timeout.Do =new Program().DoSomething;
watch.Start();
timer =new System.Threading.Timer(timerCallBack, null, , );
Console.WriteLine("4秒超时开始执行");
bool bo = timeout.DoWithTimeout(new TimeSpan(, , , ));
Console.WriteLine(string.Format("4秒超时执行结果,是否超时:{0}", bo));
Console.WriteLine("***************************************************"); timeout =new Timeout();
timeout.Do =new Program().DoSomething;
Console.WriteLine("6秒超时开始执行");
bo = timeout.DoWithTimeout(new TimeSpan(, , , ));
Console.WriteLine(string.Format("6秒超时执行结果,是否超时:{0}", bo)); timerCallBack(null); watch.Stop();
timer.Dispose();
Console.ReadLine();
}
staticvoid timerCallBack(object obj)
{
Console.WriteLine(string.Format("运行时间:{0}秒", watch.Elapsed.TotalSeconds.ToString("F2")));
}
publicvoid DoSomething()
{
// 休眠 5秒
System.Threading.Thread.Sleep(new TimeSpan(, , , ));
}
}

测试代码执行结果如下:

由上可得知:设定超时时间为4秒执行方法 DoSomething,执行结果为超时,并且在4秒后跳出方法DoSomething继续向下执行。

C#函数运行超时则终止执行(任意参数类型及参数个数通用版)

/// <summary>
/// 控制函数执行时间,超时返回null不继续执行
/// 调用方法
/// FuncTimeout.EventNeedRun action = delegate(object[] param)
/// {
///     //调用自定义函数
///     return Test(param[0].ToString(), param[1].ToString(), (DateTime)param[2]);
/// };
/// FuncTimeout ft = new FuncTimeout(action, 2000);
/// var result = ft.doAction("1", "2", DateTime.Now);
/// </summary>
public class FuncTimeout
{
    /// <summary>
    /// 信号量
    /// </summary>
    public ManualResetEvent manu = new ManualResetEvent(false);
    /// <summary>
    /// 是否接受到信号
    /// </summary>
    public bool isGetSignal;
    /// <summary>
    /// 设置超时时间
    /// </summary>
    public int timeout;
    /// <summary>
    /// 定义一个委托 ,输入参数可选,输出object
    /// </summary>
    public delegate object EventNeedRun(params object[] param);
    /// <summary>  
    /// 要调用的方法的一个委托  
    /// </summary>  
    private EventNeedRun FunctionNeedRun;
 
    /// <summary>
    /// 构造函数,传入超时的时间以及运行的方法
    /// </summary>
    /// <param name="_action">运行的方法 </param>
    /// <param name="_timeout">超时的时间</param>
    public FuncTimeout(EventNeedRun _action, int _timeout)
    {
        FunctionNeedRun = _action;
        timeout = _timeout;
    }
 
    /// <summary>
    /// 回调函数
    /// </summary>
    /// <param name="ar"></param>
    public void MyAsyncCallback(IAsyncResult ar)
    {
        //isGetSignal为false,表示异步方法其实已经超出设置的时间,此时不再需要执行回调方法。
        if (isGetSignal == false)
        {
            //放弃执行回调函数;
            Thread.CurrentThread.Abort();
        }
    }
 
    /// <summary>
    /// 调用函数
    /// </summary>
    /// <param name="input">可选个数的输入参数</param>
    /// <returns></returns>
    public object doAction(params object[] input)
    {
        EventNeedRun WhatTodo = CombineActionAndManuset;
        //通过BeginInvoke方法,在线程池上异步的执行方法。
        var r = WhatTodo.BeginInvoke(input, MyAsyncCallback, null);
        //设置阻塞,如果上述的BeginInvoke方法在timeout之前运行完毕,则manu会收到信号。此时isGetSignal为true。
        //如果timeout时间内,还未收到信号,即异步方法还未运行完毕,则isGetSignal为false。
        isGetSignal = manu.WaitOne(timeout);
 
        if (isGetSignal == true)
        {
            return WhatTodo.EndInvoke(r);
        }
        else
        {
            return null;
        }
    }
 
    /// <summary>
    /// 把要传进来的方法,和 manu.Set()的方法合并到一个方法体。
    /// action方法运行完毕后,设置信号量,以取消阻塞。
    /// </summary>
    /// <param name="input">输入参数</param>
    /// <returns></returns>
    public object CombineActionAndManuset(params object[] input)
    {
        var output = FunctionNeedRun(input);
        manu.Set();
        return output;
    }
}

C#如何控制方法的执行时间,超时则强制退出方法执行 (这个比较有用)

class Program
{ static void Main(string[] args)
{
//try the five second method with a 6 second timeout
CallWithTimeout(FiveSecondMethod, ); //try the five second method with a 4 second timeout
//this will throw a timeout exception
CallWithTimeout(FiveSecondMethod, );
} static void FiveSecondMethod()
{
Thread.Sleep();
}
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();
}
} }

C# 给某个方法设定执行超时时间 C#如何控制方法的执行时间,超时则强制退出方法执行 C#函数运行超时则终止执行(任意参数类型及参数个数通用版)的更多相关文章

  1. C#函数运行超时则终止执行(任意参数类型及参数个数通用版)

    /// <summary> /// 控制函数执行时间,超时返回null不继续执行 /// 调用方法 /// FuncTimeout.EventNeedRun action = delega ...

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

    转自:http://outofmemory.cn/code-snippet/1762/C-how-control-method-zhixingshijian-chaoshi-ze-force-quit ...

  3. Python网络编程——设定并获取默认的套接字超时时间

    Sometimes,you need to manipulate the default values of certain properties of a socket library, for e ...

  4. Quartz定时任务和IIS程序池闲置超时时间冲突解决方案

    一.问题描述 Bs项目中用Quartz功能执行一个定时任务(每隔5分钟执行一个Job),正常情况,Quartz定时任务会5分钟执行一次,但IIS程序池闲置 超时默认为20分钟,造成的结果是:定时任务只 ...

  5. springcloud之Feign、ribbon设置超时时间和重试机制的总结

    一 超时时间配置 如果在一个微服务当中对同一个接口同时配置了Hystrix与ribbon两个超时时间,则在接口调用的时候,两个计时器会同时读秒. 比如,访问一个接口需要2秒,你的ribbon配置的超时 ...

  6. sql server中 设置与查看锁的超时时间(ZT) @@LOCK_TIMEOUT

      在数据库的应用系统中,死锁是不可避免的.通过设置死锁的处理优先级方法,可以在数据库引擎中自动检测到死锁,对发生的死锁会话进行干预,从而达到解除死锁的目点,但在这种情况下,会话只能被动的等待数据库引 ...

  7. hystrix ,feign,ribbon的超时时间配置,以及原理分析

    背景,网上看到很多关于hystrix的配置都是没生效的,如: 一.先看测试环境搭建: order 服务通过feign 的方式调用了product 服务的getProductInfo 接口 //---- ...

  8. 使用timeout-decorator为python函数任务设置超时时间

    需求背景 在python代码的实现中,假如我们有一个需要执行时间跨度非常大的for循环,如果在中间的某处我们需要定时停止这个函数,而不停止整个程序.那么初步的就可以想到两种方案:第一种方案是我们先预估 ...

  9. 【Spring Cloud 源码解读】之 【如何配置好OpenFeign的各种超时时间!】

    关于Feign的超时详解: 在Spring Cloud微服务架构中,大部分公司都是利用Open Feign进行服务间的调用,而比较简单的业务使用默认配置是不会有多大问题的,但是如果是业务比较复杂,服务 ...

随机推荐

  1. Android性能优化篇

    很多App都会遇到以下几个常见的性能问题: 启动速度慢:界面跳转慢:事件响应慢:滑动和动画卡顿. 一.启动速度优化. 优化初始化任务: 1. 把一些初始化任务懒加载初始化 2. 把初始化任务并行化(异 ...

  2. NGUI Scroll List

    NGUI Scroll List 1.Add GameObject with Script UI Panel(NGUI -> UI -> NGUI Panel) and Script UI ...

  3. python的基础类源码解析——collection类

    1.计数器(counter) Counter是对字典类型的补充,用于追踪值的出现次数. ps:具备字典的所有功能 + 自己的功能 ################################### ...

  4. Yii 提示Invalid argument supplied for foreach() 等错误

    Yii 提示Invalid argument supplied for foreach() 或者 undefined variable: val等错误 只需要在对应的文件中加入error_report ...

  5. table表格中实现tbody部分可滚动,且thead部分固定

    1.想要实现表格的thead部分固定切tbody部分可滚动,就需要将thead与tbody进行分离,具体做法是 1.设置thead,tbody都为display:block: 2.设置th与td的宽度 ...

  6. centos7.0 64位系统 安装PHP 支持 nginx

    1  安装PHP所需要的扩展 yum -y install libxml2 libxml2-devel openssl openssl-devel bzip2 bzip2-devel curl cur ...

  7. Dispatcher.Invoke方法

    前一篇小猪分享过在WPF中简单的使用BackgroundWorker完成多线程操作!在那篇中小猪利用了BackgroundWorker组件对耗时比较多的操作放在了单独的BackgroundWorker ...

  8. Ubuntu user switch

    To list all users you can use: cut -d: -f1 /etc/passwd To add a new user you can use: sudo adduser n ...

  9. [UIImage resizableImageWithCapInsets:]

    [UIImage resizableImageWithCapInsets:]使用注意 转自:http://www.cnblogs.com/scorpiozj/p/3302270.html 最近在sae ...

  10. jQuery--checkbox全选

    jQuery.attr  获取/设置对象的属性值,如: $("input[name='chk_list']").attr("checked");     //读 ...