Function with Timeout

3033 단어 function
  /// <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;
        }

좋은 웹페이지 즐겨찾기