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

    }
}

  

内容来源于网络如有侵权请私信删除
你还没有登录,请先登录注册
  • 还没有人评论,欢迎说说您的想法!