zoukankan      html  css  js  c++  java
  • C#在VS2005开发环境中利用异步模式来对一个方法的执行时间进行超时控制

    using System.Threading;
    using System;
    namespace ConsoleApplication4
    {
        public class Program
        {
            static void Main(string[] args)
            {
                try
                {
                    String str = "excuting";
                    myDel del = new myDel(Method);
                    CallWithTimeout(del,1200,str);
                    Console.WriteLine("success");
    
                }
                catch (Exception)
                {
                    Console.WriteLine("fail");
                }
            }
    
            static void Method(String str)
            {
                Console.WriteLine(str);
                Thread.Sleep(1000);
            }
    
            public delegate void myDel(string str);
            static void CallWithTimeout(myDel del,int timeoutMilliseconds,String str)
            {
                ThreadStart threadStart = new ThreadStart(delegate()
                {
                    if (null != del)
                    {
                        del(str);//委托调用
                    }
                });
                Thread thread = new Thread(threadStart);
    
                IAsyncResult result = del.BeginInvoke(str, null, null);
                if (result.AsyncWaitHandle.WaitOne(timeoutMilliseconds))
                {
                    del.EndInvoke(result);
                }
                else
                {
                    thread.Abort();
                    throw new TimeoutException();
                }
            }
    
        }
    }
    

      

  • 相关阅读:
    css属性操作2(外边距与内边距<盒子模型>)
    css的属性操作1
    css伪类
    属性选择器二
    属性选择器1
    03_MySQL重置root密码
    02_Mysql用户管理之Navicat下载及安装
    18.扩散模型
    17.广播模型
    16.友谊悖论
  • 原文地址:https://www.cnblogs.com/Acamy/p/6613654.html
Copyright © 2011-2022 走看看