Action、Func,实现超时中断进程

论坛 期权论坛 脚本     
匿名技术用户   2020-12-21 18:01   73   0

Action、Func,实现超时中断进程

概述
1、Action用于没有返回值的方法(参数可以根据自己情况进行传递)
2、Func用于有返回值的方法(同样参数根据自己情况情况)

以下为延迟函数,其中Action action为带有参数的方法,将temp传过去。

  //超过时间,自动中断进程
        static void CallWithTimeout(Action<int> action,int temp, int timeoutMilliseconds)
        {
            Thread threadToKill = null;
            Action wrappedAction = () =>
            {
                threadToKill = Thread.CurrentThread;
                action(temp);
            };

            IAsyncResult result = wrappedAction.BeginInvoke(null, null);
            if (result.AsyncWaitHandle.WaitOne(timeoutMilliseconds))
            {
                wrappedAction.EndInvoke(result);
            }
            else
            {
                threadToKill.Abort();
                throw new TimeoutException();
            }
        }

定义的带参数的函数

        public void MyAction(int s)
        {
            while (s<=0) {
                s--;
            }
        }

执行的函数,如果超过1000ms,则会中断进程

        public void test()
        {
            Action<int> ac = new Action<int>(MyAction);
            CallWithTimeout(ac, 66666666,1000);
        }

Func用于有返回值的场景:

        public string MyAction(int s)
        {
            while (s<=0) {
                s--;
            }
            return "123";
        }
static void CallWithTimeout(Func<int, string> action,int temp, int timeoutMilliseconds)

调用:
Func<int,string> 中,第一个参数是参数,最后一个参数是返回值

        public void test()
        {
            Func<int,string> f = MyAction;
            var s = f(1);//返回值为s
            CallWithTimeout(f, 6,1000);
        }
        ```
分享到 :
0 人收藏
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

积分:7942463
帖子:1588486
精华:0
期权论坛 期权论坛
发布
内容

下载期权论坛手机APP