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

本文介绍如何利用C#中的Action和Func委托来实现进程的超时中断功能。通过具体的代码示例,展示了如何定义并使用这些委托类型来控制长时间运行的任务,并在指定时间内未完成时中断进程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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);
        }
        ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值