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进行服务间的调用,而比较简单的业务使用默认配置是不会有多大问题的,但是如果是业务比较复杂,服务 ...
随机推荐
- Spring中映射Mongodb中注解的解释
spring-data-mongodb中的实体映射是通过MongoMappingConverter这个类实现的.它可以通过注释把java类转换为mongodb的文档. 它有以下几种注释: @Id - ...
- linux笔记:用户和用户组管理-用户管理命令
useradd(添加用户.在使用useradd添加一个用户后,必须使用passwd给该用户设置密码,该用户才能登陆): passwd(设置或修改用户密码): usermod(修改用户信息): chag ...
- MySQL学习笔记--基本操作
1.登录数据库 在命令行输入 "mysql -u username -p" 回车后输入密码 2.选择数据库 USE datebase name,选择要操作的数据库 3.显示所有数据 ...
- sql注入基于错误-单引号-字符型
查找注入点 在url中: 1. ' 2. and 1=1/and 1=2 3. 随即输入(整形) 4. -1/+1回显上下页面(整形) 5. and sleep(5) (判断页面返回时间) 判断有 ...
- public && protected && private
http://www.cnblogs.com/BeyondAnyTime/archive/2012/05/23/2514964.html 1.public继承不改变基类成员的访问权限. 2.priva ...
- jquery 常用基础方法
1 jquery常用方法: 2 取得标签元素里面内容与修改: 3 1.text()方法: 4 $(document).ready(function(){ 5 //alert("文档加载完毕& ...
- Linux字符设备
一.linux系统将设备分为3类:字符设备.块设备.网络设备. 字符设备:是指只能一个字节一个字节读写的设备,不能随机读取设备内存中的某一数据,读取数据需要按照先后数据.字符设备是面向流的设备,常见的 ...
- JavaScript中的eval()函数
和其他很多解释性语言一样,JavaScript同样可以解释运行由JavaScript源代码组成的字符串,并产生一个值.JavaScript通过全局函数eval()来完成这个工作. eval(“1+2” ...
- (转)oracle 存储过程 带游标作为OUT参数输出
(转)oracle 存储过程 带游标作为OUT参数输出 存储过程返回OUT参数的游标 例子. 包中带过程 要自己定义一个type [cur_name] is ref cursor游标,返回的时候就直接 ...
- iOS 7 UITableview 在Plain模式下 设置背景颜色无效
在iOS6的时候,设置Plain模式下table的颜色 通过[self.table setBackgroundColor:[UIColor red]]; 就可以看到一个满身通红的tableView 但 ...