Function with Timeout

 

  /// <summary>
        /// if one drive broken, use [Directory.Exists] may cause 10 seconds,
        /// so design this function with timeout.
        /// </summary>
        /// <param name="path"></param>
        /// <param name="timeout"></param>
        /// <returns></returns>
        public static bool? CheckPathExistWithTimeout(string path, double timeout)
        {
            bool isWait = true;
            bool? isReady = null;
            CancellationTokenSource cancelSource = new CancellationTokenSource();
            Task.Factory.StartNew(() =>
            {
                isReady = Directory.Exists(path);
                isWait = false;
            }, cancelSource.Token);

            int ticks = 0;
            while (isWait)
            {
                if (ticks >= timeout * 1000)
                {
                    break;
                }
                ticks++;
                Thread.Sleep(TimeSpan.FromMilliseconds(1));
            }
            cancelSource.Cancel();
            return isReady;
        }

 

posted @ 2012-11-07 14:35  xiaokang088  阅读(187)  评论(0编辑  收藏  举报