具有timeout 功能的函数调用

做项目的时候有时经常会需要一个带有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);   
            }
        }
posted on 2016-04-07 21:34  禅宗花园...迷失的佛 阅读( ...) 评论( ...) 编辑 收藏

转载于:https://www.cnblogs.com/VectorZhang/p/5365577.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值