多线程操作同一文件进行读写
通过锁方式,只能允许单个线程操作文件,避免同时操作同一文件造成“由于另一进程正在访问...”的错误
public class LogServices { private static LogServices _instance; private static readonly object _lock = new object(); private static readonly object _lockFile=new object(); private LogServices() { } public static LogServices Instance() { if (_instance == null) { lock (_lock) { if (_instance == null) { _instance = new LogServices(); return _instance; } else{ return _instance; } } } else { return _instance; } } public bool GenerateLogFile(string strText, string folder = "") { //lock (_lockFile) { string filePath = Path.Combine(Directory.GetCurrentDirectory(), "Log"); bool bresult = false; string currentDate = DateTime.Now.ToString("yyyyMMdd"); string currentTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"); if (filePath.Length <= 0) return bresult; else { filePath = string.IsNullOrWhiteSpace(folder) ? filePath : Path.Combine(filePath, folder); lock (_lockFile) { //路径不存在则创建路径 if (!Directory.Exists(filePath)) { Directory.CreateDirectory(filePath); } filePath = Path.Combine(filePath, currentDate + folder + ".txt"); //文件不存在则生成文件 if (!File.Exists(filePath)) { File.Create(filePath).Close(); } StreamWriter sw = new StreamWriter(filePath, true, System.Text.Encoding.Default);//第一个参数代表路径,第二个参数表示文件是否覆盖还是在原有文件基础上添加,第三个参数代表编码格式 sw.WriteLine(currentTime + ":" + strText);//写入txt文件 bresult = true; sw.Flush(); sw.Close(); } } return bresult; } } }