C#实现函数的超时退出功能

主要是用到了System.Threading.Tasks.TaskFactory的StartNew()函数

 

        private static void Main(string[] args)
        {
            Console.WriteLine("Begin:" + DateTime.Now);
            bool ret = Process(string.Empty, 10000);
            Console.WriteLine("Result={0}", ret);
            Console.WriteLine("End:" + DateTime.Now);
            Console.WriteLine("Press any key to exit...");
            Console.ReadKey(true);
            
        }

        private static bool Process(string param, int timeout)
        {
            bool ret = false;
            new System.Threading.Tasks.TaskFactory().StartNew(() => {
                ret = LongTimeFunc();
            }).Wait(timeout);

            return ret;
        }

        private static bool LongTimeFunc()
        {
            System.Threading.Thread.Sleep(5000);
            return true;
        }

 

你可能感兴趣的:(C#)