一、同步讀寫文件(在並發情況下不會發生文件被占用異常)
static void Main(string[] args)
{
Parallel.For(0, 10000, e =>
{
string str = "測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試\r\n"; using (FileStream fs = new FileStream("d:\\a.txt", FileMode.Append, FileAccess.Write, FileShare.ReadWrite, 1024, false)) { byte[] bty = Encoding.UTF8.GetBytes(str); fs.Write(bty, 0, bty.Length); fs.Close(); } });
} 二、異步讀寫文件(在並發情況下不會發生文件被占用異常)
static void Main(string[] args)
{
Parallel.For(0, 10000, e =>
{
string str = "測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試\r\n";
FileStream fs = new FileStream("d:\\a.txt", FileMode.Append, FileAccess.Write, FileShare.ReadWrite, 1024, false);
byte[] bty = Encoding.UTF8.GetBytes(str);
fs.BeginWrite(bty, 0, bty.Length, new AsyncCallback(EndWriteCallback), fs);
});
Console.WriteLine("執行完成");
Console.ReadKey();
}
private static void EndWriteCallback(IAsyncResult asr) { using (Stream str = (Stream)asr.AsyncState) { str.EndWrite(asr); Console.WriteLine("異步寫入結束"); } }