我听说
SemaphoreSlim
可以限制线程访问某些内容,但我不知道它在 async
上下文中的确切用法?
if (!LOGS_FILE.Equals(string.Empty) && File.Exists(LOGS_FILE))
{
using (StreamWriter STREAM_WRITER = new StreamWriter(LOGS_FILE, true))
{
STREAM_WRITER.WriteLine(LOG);
}
}
if (IsDebuggerAttached())
{
System.Diagnostics.Debug.WriteLine(LOG);
}
ALL_LOGS += LOG + "\n";
正如 @Panagiotis Kanavos 指出的,使用
lock() { }
块更好,这就是你可以如何实现它而不是 SemaphoreSlim:
object lockObject = new object(); //Global field
...
if (!LOGS_FILE.Equals(string.Empty) && File.Exists(LOGS_FILE))
{
lock(lockObject)
{
using (StreamWriter STREAM_WRITER = new StreamWriter(LOGS_FILE, true))
{
STREAM_WRITER.WriteLine(LOG);
}
}
}
if (IsDebuggerAttached())
{
System.Diagnostics.Debug.WriteLine(LOG);
}
ALL_LOGS += LOG + "\n";
考虑使用日志库,这样你就不会在处理并发调用和其他事情时感到困惑。
试试这个:
try
{
SEMAPHORE_SLIM.Wait();
if (!LOGS_FILE.Equals(string.Empty) && File.Exists(LOGS_FILE))
{
using (StreamWriter STREAM_WRITER = new StreamWriter(LOGS_FILE, true))
{
STREAM_WRITER.WriteLine(LOG);
}
}
if (IsDebuggerAttached())
{
System.Diagnostics.Debug.WriteLine(LOG);
}
ALL_LOGS += LOG + "\n";
}
finally
{
SEMAPHORE_SLIM.Release();
}
编辑:添加了 try finally 块