C# 给某个方法设定执行超时时间 C#如何控制方法的执行时间,超时则强制退出方法执行 C#函数运行超时则终止执行(任意参数类型及参数个数通用版)
我自己写的
/// <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#函数运行超时则终止执行(任意参数类型及参数个数通用版)的更多相关文章
- C#函数运行超时则终止执行(任意参数类型及参数个数通用版)
/// <summary> /// 控制函数执行时间,超时返回null不继续执行 /// 调用方法 /// FuncTimeout.EventNeedRun action = delega ...
- C#如何控制方法的执行时间,超时则强制退出方法执行
转自:http://outofmemory.cn/code-snippet/1762/C-how-control-method-zhixingshijian-chaoshi-ze-force-quit ...
- Python网络编程——设定并获取默认的套接字超时时间
Sometimes,you need to manipulate the default values of certain properties of a socket library, for e ...
- Quartz定时任务和IIS程序池闲置超时时间冲突解决方案
一.问题描述 Bs项目中用Quartz功能执行一个定时任务(每隔5分钟执行一个Job),正常情况,Quartz定时任务会5分钟执行一次,但IIS程序池闲置 超时默认为20分钟,造成的结果是:定时任务只 ...
- springcloud之Feign、ribbon设置超时时间和重试机制的总结
一 超时时间配置 如果在一个微服务当中对同一个接口同时配置了Hystrix与ribbon两个超时时间,则在接口调用的时候,两个计时器会同时读秒. 比如,访问一个接口需要2秒,你的ribbon配置的超时 ...
- sql server中 设置与查看锁的超时时间(ZT) @@LOCK_TIMEOUT
在数据库的应用系统中,死锁是不可避免的.通过设置死锁的处理优先级方法,可以在数据库引擎中自动检测到死锁,对发生的死锁会话进行干预,从而达到解除死锁的目点,但在这种情况下,会话只能被动的等待数据库引 ...
- hystrix ,feign,ribbon的超时时间配置,以及原理分析
背景,网上看到很多关于hystrix的配置都是没生效的,如: 一.先看测试环境搭建: order 服务通过feign 的方式调用了product 服务的getProductInfo 接口 //---- ...
- 使用timeout-decorator为python函数任务设置超时时间
需求背景 在python代码的实现中,假如我们有一个需要执行时间跨度非常大的for循环,如果在中间的某处我们需要定时停止这个函数,而不停止整个程序.那么初步的就可以想到两种方案:第一种方案是我们先预估 ...
- 【Spring Cloud 源码解读】之 【如何配置好OpenFeign的各种超时时间!】
关于Feign的超时详解: 在Spring Cloud微服务架构中,大部分公司都是利用Open Feign进行服务间的调用,而比较简单的业务使用默认配置是不会有多大问题的,但是如果是业务比较复杂,服务 ...
随机推荐
- css学习笔记 2
css中的简写: 颜色的简写有三种:十六进制的形式.rgb(a).颜色名称. 单位的省略:当属性值为0px时,可以简写为0. margin和padding的简写,不多说了. border的简写:bor ...
- 基础向量运算-2D镜面反射
如图M为镜面,A为入射光,B为反射光,已知A与M的向量坐标,求B的向量表示. 我们添加辅助向量C. 有以下性质. B = 2 * C - A. [1] |C| = |A| * cos(alpah).A ...
- Rhel6-mpich2 hpc集群配置文档
系统环境: rhel6 x86_64 iptables and selinux disabled 主机: 192.168.122.121 server21.example.com 192.168.12 ...
- [HB2014 Week5] Allot 人员分配
这两天决心专门搞好网络流了 - - 题解在什么瞎胡搞跟我说要连n+2和n+1容量为无穷的边…我看了下std才做的… 坑死人的地方就是,需要求多次网络流,每次别忘了把流给清空了…这次是用链表所以专门写了 ...
- Spark Streaming之旅
1. 打开spark-shell 2. 建立StreamingContext import org.apache.spark.streaming._ import org.apache.spark.s ...
- Xceed Ultimate Suite Xceed界面控件套包下载
Xceed Ultimate Suites是一款用户界面.数据处理套包,从.NET/WPF/silverLight平台到ActiveX下包含了65个子控件,以及Xceed公司的所有控件,具有表格.风格 ...
- 修改 UISearchBar cancelButton 样式
今天收到个问题,老大让我修改UISearchBar cancelButton的样式本来以为很简单的一个活,没想到让我长知识了. 开始在网上搜到的方法和我想象的一样,通过遍历Subviews获得butt ...
- megapix-image插件 使用Canvas压缩图片上传 解决手机端图片上传功能的问题
最近在弄微信端的公众号.订阅号的相关功能,发现原本网页上用的uploadify图片上传功能到手机端有的手机类型上就不能用了,比如iphone,至于为啥我想应该不用多说了吧(uploadify使用fla ...
- sqoop连接oracle与mysql&mariadb的错误
错误说明: 由于我的hadoop的集群是用cloudera manager在线自动安装的,因此他们的安装路径必须遵循cloudera的规则,这里只有查看cloudera的官方文档了,请参考:http: ...
- uoot启动过程
1.从我们的start_armboot开始讲起 u-boot整体由汇编段和C语言段外加连接脚本组成.关于汇编段请看我之前的博客<u-boot源码汇编段简要分析>,好,让我们进入start_ ...