所谓同步:如果在代码中调用了一个方法,则必须等待该方法所有的代码执行完毕之后,才能回到原来的地方执行下一行代码。
异步:如果不等待调用的方法执行完,就执行下一行代码。
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(); } } }