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();
                }
            }
    
        }
    }
    

      

  • 相关阅读:
    Chrome开发者工具详解(1)
    Chrome开发者工具详解(2)
    Ubuntu ADSL拨号上网
    Bash中单引号和双引号的区别
    建立菜单
    波浪号和Hyphen扩展
    标准IO和重定向
    Bash变量扩展修改符
    mysql主键约束和唯一性约束
    Here文档
  • 原文地址:https://www.cnblogs.com/Acamy/p/6613654.html
Copyright © 2011-2022 走看看