在C#/.NET中,將文本內容寫入文件最簡單的方法是調用 File.WriteAllText() 方法,但這個方法沒有異步的實現,要想用異步,只能改用有些復雜的 FileStream.WriteAsync() 方法。
使用 FileStream.WriteAsync() 有2個需要注意的地方,1是要設置bufferSize,2是要將useAsync這個構造函數參數設置為true,示例調用代碼如下:
public async Task CommitAsync() { var bits = Encoding.UTF8.GetBytes("{\"text\": \"test\"}"); using (var fs = new FileStream( path: @"C:\temp\test.json", mode: FileMode.Create, access: FileAccess.Write, share: FileShare.None, bufferSize: 4096, useAsync: true)) { await fs.WriteAsync(bits, 0, bits.Length); } }
看這個方法的幫助文檔中對useAsync參數的說明:
// useAsync: // Specifies whether to use asynchronous I/O or synchronous I/O. However, note // that the underlying operating system might not support asynchronous I/O, // so when specifying true, the handle might be opened synchronously depending // on the platform. When opened asynchronously, the System.IO.FileStream.BeginRead(System.Byte[],System.Int32,System.Int32,System.AsyncCallback,System.Object) // and System.IO.FileStream.BeginWrite(System.Byte[],System.Int32,System.Int32,System.AsyncCallback,System.Object) // methods perform better on large reads or writes, but they might be much slower // for small reads or writes. If the application is designed to take advantage // of asynchronous I/O, set the useAsync parameter to true. Using asynchronous // I/O correctly can speed up applications by as much as a factor of 10, but // using it without redesigning the application for asynchronous I/O can decrease // performance by as much as a factor of 10.
從中可以得知,只有設置useAsync為true,才真正使用上了異步IO。