Skip to content

Instantly share code, notes, and snippets.

@ruyut
Created June 13, 2021 02:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ruyut/f925aec4eb148632a9ad8e5b1360aa30 to your computer and use it in GitHub Desktop.
Save ruyut/f925aec4eb148632a9ad8e5b1360aa30 to your computer and use it in GitHub Desktop.
[C#] 多執行緒快速讀寫同個檔案 強迫列隊
using System;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
namespace Ruyut
{
public class SyncWriteFile
{
private static readonly ManualResetEvent ManualResetEvent = new ManualResetEvent(true);
private static readonly string FileName = "D:\\log.log";
/**
* @s 輸入的文字
* @append 是否要"附加" {true:接續文字後面, false:覆蓋整份文件}
*/
private static async Task Output(string s, bool append = true)
{
ManualResetEvent.WaitOne();
using (StreamWriter streamWriter = new StreamWriter(FileName, append))
{
streamWriter.WriteLineAsync($"{DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss")} {s}" );
streamWriter.Close();
}
ManualResetEvent.Set();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment