c# 高效讀寫文件


一、同步讀寫文件(在並發情況下不會發生文件被占用異常)

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("異步寫入結束");
            }
        }

 


免責聲明!

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



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