C#幾種異步編程


所謂同步:如果在代碼中調用了一個方法,則必須等待該方法所有的代碼執行完畢之后,才能回到原來的地方執行下一行代碼。

異步:如果不等待調用的方法執行完,就執行下一行代碼。

閱讀原文

namespace AsyncProgram
{
    class Program
    {
        //Calculate the folder's total size
        private static Int64 CalculateFolderSize(string FolderName)
        {
            if (Directory.Exists(FolderName) == false)
            {
                throw new DirectoryNotFoundException("文件不存在");
            }
            DirectoryInfo rootDir = new DirectoryInfo(FolderName);
            //Get all subfolders
            DirectoryInfo[] childDirs = rootDir.GetDirectories();
            //Get all files of current folder
            FileInfo[] files = rootDir.GetFiles();
            Int64 totalSize = 0;
            //sum every file size
            foreach (FileInfo file in files)
            {
                totalSize += file.Length;

            }
            //sum every folder
            foreach (DirectoryInfo dir in childDirs)
            {
                totalSize += CalculateFolderSize(dir.FullName);
            }
            return totalSize;

        }

        static void Main(string[] args)
        {
            Int64 size;
            String FolderName;
            Console.WriteLine("Please input the name of folder (C:\\Windows):");
            FolderName = Console.ReadLine();
            size = CalculateFolderSize(FolderName);
            Console.WriteLine("\nThe size of folder {0} is {1}字節\n", FolderName, size);
            Console.ReadKey();
        }
    }
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM