C#如何控制方法的执行时间,超时则强制退出方法执行

这篇博客探讨了一个用于异步调用并带有超时控制的C#方法实现,通过`CallWithTimeout`函数来确保函数执行不会无限期等待。在超时时,该方法会终止线程。示例中展示了如何将此方法应用于一个模拟的`FiveSecondMethod`,在指定毫秒内等待其返回,如果超时则显示相应提示。此外,还提供了一个修改后的版本`CallWithTimeout2`,用于处理带有两个参数的方法。
摘要由CSDN通过智能技术生成
public static R  CallWithTimeout<P, R>(Func<P, R> action, P p, out bool isTimeout, int millisecondsTimeout = Timeout.Infinite)
        {
            Thread threadToKill = null;
            R r = default(R);
            Action wrappedAction = () =>
            {
                threadToKill = Thread.CurrentThread;
                r = action(p);
            };

            IAsyncResult result = wrappedAction.BeginInvoke(null, null);
            if (result.AsyncWaitHandle.WaitOne(millisecondsTimeout))
            {
                wrappedAction.EndInvoke(result);
                isTimeout = false;

            }
            else
            {
                //threadToKill.Abort();
                //throw new TimeoutException();
                Action abortAction = delegate
                {
                    threadToKill.Abort();
                };
                abortAction.BeginInvoke(null, null);
                isTimeout = true;
            }
            return r;
        }

调用

public string FiveSecondMethod(int t)
        {
           // p = "1";
            Thread.Sleep(t);
            return "false" ;
        }      


private void button3_Click(object sender, EventArgs e)
        {
            int t1 = int.Parse(textBox1.Text);
            bool btime=false;
            //  MyMethodB<string>(new Func<string, int>(MyMethodA), "feige");

            //   bool b =  CallWithTimeout<int,bool>(new Func<int, bool>(FiveSecondMethod), t1,out btime, t1);
            string s= CallWithTimeout(FiveSecondMethod, t1, out btime, t1);
        }

在这里注意,返回值必须统一类型,R类型即为我们所有运行函数的类型。

 

 

下面这个是我自己改的,不知道是不是符合语法,或者是不是写的有问题,嗯,总之就这么用了,传两个参数。

        static void CallWithTimeout2(Action<int ,string> action ,int CIO,string num, int timeoutMilliseconds)
        {
            Thread threadToKill = null;
            Action wrappedAction = () =>
            {
                threadToKill = Thread.CurrentThread;
              
                action(CIO, num);
            };

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

调用

   private void button10_Click(object sender, EventArgs e)
        {
            CallWithTimeout2(WriteCar6, 30, "0040", 1000);
            readCX = 5;
            //Cx6 = 1;
            //   string Car6 = string.Empty;
            //    CIODZ = 30;   //CIO30.06      车型6
            //   Car6 = getres1(("0040").ToString()).ToString();
            //if (Car6 == "")
            //{
            //    MessageBox.Show("写入不成功,请重新操作!");
            //}

        }


  public void WriteCar6(int CIO ,string n)
        {
            string Car1 = string.Empty;

            CIODZ = CIO;   //CIO30.01      车型1
            Car1 = getres1((n).ToString()).ToString();
        }

这里应该是可以简写的,知道的帮我修改下,谢谢。getres1()是一个处理算法,太多不写了。

 

以上内容均为剽窃后修改。

原内容参考:https://www.cnblogs.com/CoreXin/p/12303622.html

 

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值