做项目的时候有时经常会需要一个带有timeout功能的函数调用。

比如从后台读数据并期望在给定时间内返回。借此机会包装了一个简单的C# class, 直接上代码吧.

public class TimeoutInvokerWrapper
{
private ManualResetEvent mTimeoutObject;
private bool mBoTimeout;
private Func<object, object> doHandler; public string Error { get; private set; }
public object Result { get; private set; } public TimeoutInvokerWrapper(Func<object, object> handler)
{
this.doHandler = handler;
this.mTimeoutObject = new ManualResetEvent(true);
} public bool DoWithTimeout(object input, TimeSpan timeSpan)
{
if (this.doHandler == null)
{
return false;
} this.mTimeoutObject.Reset();
this.mBoTimeout = true; this.doHandler.BeginInvoke(input, DoAsyncCallBack, null);
if (!this.mTimeoutObject.WaitOne(timeSpan, false))
{
this.mBoTimeout = true;
} return this.mBoTimeout;
} private void DoAsyncCallBack(IAsyncResult result)
{
try
{
this.Result = this.doHandler.EndInvoke(result);
this.mBoTimeout = false;
}
catch (Exception ex)
{
this.mBoTimeout = true;
this.Error = ex.ToString();
}
finally
{
this.mTimeoutObject.Set();
}
}
}

该类可以这样使用

public static void Main(string[] args)
{
Func<object, object> func = (obj) => { return obj.ToString(); }; TimeoutInvokerWrapper wrapper = new TimeoutInvokerWrapper(func);
bool isTimeout = wrapper.DoWithTimeout(123, TimeSpan.FromSeconds(2));
if (isTimeout)
{
System.Console.WriteLine("function call timeout.");
}
else if (!string.IsNullOrEmpty(wrapper.Error))
{
System.Console.WriteLine("function call does not timeout but throw exception.");
}
else
{
System.Console.WriteLine("call succeed.")
System.Console.WriteLine(wrapper.Result);
}
}

具有timeout 功能的函数调用的更多相关文章

  1. [转载]Process工具类,提供设置timeout功能

    FROM:http://segmentfault.com/blog/lidonghao/1190000000372535 在前一篇博文中,简单介绍了如何使用Process类来调用命令行的功能,那样使用 ...

  2. jsContext全局函数调用与对象函数调用、evaluateScript

    evaluateScript:兼具js加载(生成具体的上下文)(函数与通用变量的加载),与函数执行的功能: 函数调用的方式有两种: 1)获取函数(对象),然后执行调用: [context[@" ...

  3. 让fetch也可以timeout

    原生的HTML5 API fetch并不支持timeout属性,习惯了jQuery的ajax配置的同学,如果一时在fetch找不到配置timeout的地方,也许会很纠结.fetch 的配置 API 如 ...

  4. 【ssm】spring功能讲解

    概览 Spring5框架包含许多特性,负责管理项目中的所有对象,并被很好地组织在下图所示的模块中 核心容器:由spring-beans.spring-core.spring-context.sprin ...

  5. 从linux源码看socket(tcp)的timeout

    从linux源码看socket(tcp)的timeout 前言 网络编程中超时时间是一个重要但又容易被忽略的问题,对其的设置需要仔细斟酌.在经历了数次物理机宕机之后,笔者详细的考察了在网络编程(tcp ...

  6. poll调用深入解析

    poll调用深入解析http://blog.csdn.net/zmxiangde_88/article/details/8099049 poll调用和select调用实现的功能一样,都是网络IO利用的 ...

  7. select、poll、epoll

    1.概念 select.poll.epoll都是事件触发机制,当等待的事件发生就触发进行处理,用于I/O复用 2.简单例子理解 3.select函数 3.1函数详解 int select(int ma ...

  8. Java并发编程系列-(9) JDK 8/9/10中的并发

    9.1 CompletableFuture CompletableFuture是JDK 8中引入的工具类,实现了Future接口,对以往的FutureTask的功能进行了增强. 手动设置完成状态 Co ...

  9. Linux Socket 网络编程

    Linux下的网络编程指的是socket套接字编程,入门比较简单.在学校里学过一些皮毛,平时就是自学玩,没有见识过真正的socket编程大程序,比较遗憾.总感觉每次看的时候都有收获,但是每次看完了之后 ...

随机推荐

  1. Centos 6.5 下安装socket5代理

    ---恢复内容开始--- 1. 安装 先安装依赖库 yum -y install gcc gcc-c++ automake make pam-devel openldap-devel cyrus-sa ...

  2. PHP操作MongoDB学习(转)

    1  mongodb启动时,设置启动项 C:\>mongodb\bin\mongod --config C:\mongodb.conf 其中mongodb.conf为:    dbpath = ...

  3. WPF RichTextBox设置文本颜色

    //追加 txtResult.Document.Blocks.Add(new Paragraph(new Run("add by run") { Foreground = Brus ...

  4. Linux探秘之用户态与内核态

    一. Unix/Linux的体系架构 如上图所示,从宏观上来看,Linux操作系统的体系架构分为用户态和内核态(或者用户空间和内核).内核从本质上看是一种软件——控制计算机的硬件资源,并提供上层应用程 ...

  5. Android 使用NDK编译sipdroid Library

    sipdroid是一款开源的运行于Android平台上的voip,目前支持音频和视频通话: 项目拖管地址:http://code.google.com/p/sipdroid/ 下载源代码,导入ecli ...

  6. BZOJ 1251 序列终结者(Splay)

    题目大意 网上有许多题,就是给定一个序列,要你支持几种操作:A.B.C.D.一看另一道题,又是一个序列要支持几种操作:D.C.B.A.尤其是我们这里的某人,出模拟试题,居然还出了一道这样的,真是没技术 ...

  7. Can't get WebApplicationContext object from ContextRegistry.GetContext(): Resource handler for the 'web' protocol is not defined

    I'm stucked in configuring my web.config file under a web forms project in order to get an instance ...

  8. winform用户控件

    用途用户控件包含Time控件和一个lable控件,一个ToolStrip控件,每隔一秒显示一次时间     1. 生成用户控件   新建一个项目类型为用户控件   注意定义类名,此类名为以后工具箱中显 ...

  9. C#基础总结之七面向对象知识点总结1

    class Class //定义一个类 名字是Class { ; string NAME; string deptName; ; //如果是常量 只能获取,不能赋值 public string Nam ...

  10. NHibernate 使用CreateSQLQuery进行查询

    涉及的表:Cake{Id ,CakeName } CakeSize{ CakeId,-为外键,对应Cake表的字段Id Size } (其中ISession session = NHibernateH ...