所謂同步:如果在代碼中調用了一個方法,則必須等待該方法所有的代碼執行完畢之后,才能回到原來的地方執行下一行代碼。
異步:如果不等待調用的方法執行完,就執行下一行代碼。
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(); } } }