Created
June 13, 2021 02:15
-
-
Save ruyut/f925aec4eb148632a9ad8e5b1360aa30 to your computer and use it in GitHub Desktop.
[C#] 多執行緒快速讀寫同個檔案 強迫列隊
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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