C#使用讀寫鎖解決多線程並發寫入文件時線程同步的問題
阿新 • • 發佈:2018-08-03
fin 問題 final [] 解決 同步 write main sta
讀寫鎖是以 ReaderWriterLockSlim 對象作為鎖管理資源的,不同的 ReaderWriterLockSlim 對象中鎖定同一個文件也會被視為不同的鎖進行管理,這種差異可能會再次導致文件的並發寫入問題,所以 ReaderWriterLockSlim 應盡量定義為只讀的靜態對象。
多線程同時寫入文件
class Program { static int writeCount = 0; static int wrongCount = 0; static void Main(string[] args) { Test(); }static void Test() { //叠代運行寫入內容,由於多個線程同時寫入同一個文件將會導致錯誤 Parallel.For(0, 100, e => { try { writeCount++; var logFilePath = "/test.txt"; var now = DateTime.Now;var logContent = string.Format("Tid: {0}{1} {2}=>{3}\r\n", Thread.CurrentThread.ManagedThreadId.ToString().PadRight(4), now.ToLongDateString(), now.ToLongTimeString(), writeCount); File.AppendAllText(logFilePath, logContent); } catch (Exception ex) { wrongCount++; Console.WriteLine("累計失敗" + wrongCount + "次"); Console.WriteLine(ex.Message); throw; } }); Console.Read(); } }
運行結果
只有部分數據寫入了文件
多線程使用讀寫鎖同步寫入文件
class Program { static int writeCount = 0; static int wrongCount = 0; static void Main(string[] args) { Test(); } static ReaderWriterLockSlim writeLock = new ReaderWriterLockSlim(); static void Test() { //叠代運行寫入內容 Parallel.For(0, 100, e => { try { writeLock.EnterWriteLock(); writeCount++; var logFilePath = "/test.txt"; var now = DateTime.Now; var logContent = string.Format("Tid: {0}{1} {2}=>{3}\r\n", Thread.CurrentThread.ManagedThreadId.ToString().PadRight(4), now.ToLongDateString(), now.ToLongTimeString(), writeCount); File.AppendAllText(logFilePath, logContent); } catch (Exception ex) { wrongCount++; Console.WriteLine("累計失敗" + wrongCount + "次"); Console.WriteLine(ex.Message); throw; } finally { writeLock.ExitWriteLock(); } }); Console.Read(); } }
運行成功,數據全部寫入文件
C#使用讀寫鎖解決多線程並發寫入文件時線程同步的問題