gpt4 book ai didi

c# - 如何使静态类线程安全?

转载 作者:行者123 更新时间:2023-12-01 23:51:34 25 4
gpt4 key购买 nike

我有一个简单的静态日志记录类。但是,它绝对不是线程安全的,因为每个调用都尝试写入同一个文件。我遇到这些异常:

The process cannot access the file 'logfile.txt' because it is being used by another process.
at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
...

使其线程安全的最佳方法是什么?

public static class Logger
{
private static readonly string LOG_FILENAME = "logfile.txt";
private static readonly string LOG_FOLDER = System.IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "App name");
private static readonly string LOG_FULLPATH = System.IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "App name", LOG_FILENAME);

public static void LogMessageToFile(string msg)
{
msg = string.Format("{0:G}: {1}{2}", DateTime.Now, msg, Environment.NewLine);
File.AppendAllText(LOG_FULLPATH, msg);
}
}

作为日志记录功能,我希望能够从代码的许多不同部分访问它(因此,为什么我选择它是静态的)。但是,我想象为了使其线程安全,我总是必须将一个公共(public)对象传递给 lock() ,我认为这违背了静态函数的目的。或者事实并非如此?

最佳答案

public static class Logger
{
private static readonly string LOG_FILENAME = "logfile.txt";
private static readonly string LOG_FOLDER = System.IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "App name");
private static readonly string LOG_FULLPATH = System.IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "App name", LOG_FILENAME);

private static Object theLock=new Object();

public static void LogMessageToFile(string msg)
{
msg = string.Format("{0:G}: {1}{2}", DateTime.Now, msg, Environment.NewLine);
lock (theLock)
{
File.AppendAllText(LOG_FULLPATH, msg);
}
}
}

关于c# - 如何使静态类线程安全?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16533285/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com