我用以下2个办法建的日志,
public static void Write(this string _uMess) { StringBuilder sb = new StringBuilder(); sb.Append(string.Format("记录时间: {0}{2}自定义信息: {1}{2}--------------------------------------------------------------------------------------------------------------------", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), _uMess, Environment.NewLine)); string _msg = sb.ToString(); WriteExceptionLog(_msg); Thread th = new Thread(delegate() { lock (locker) { WriteExceptionLog(_msg); } }); th.Start(); while (!th.IsAlive) { Thread.Sleep(50); } // Use the Join method to block the current thread // until the object's thread terminates. th.Join(); } /// <summary> /// 記錄错误信息 /// </summary> private static void WriteExceptionLog(string _filePath, string _errMsg) { lock (locker) { IOUtils.CreateFile(_filePath); } try { //Thread.Sleep(500); using (FileStream fs = new FileStream(_filePath, FileMode.Append, FileAccess.Write, FileShare.ReadWrite)) { StreamWriter sw = new StreamWriter(fs); sw.WriteLine(_errMsg); sw.Flush(); sw.Dispose(); } } catch (IOException) { } catch (Exception) { } }
我发现,当新建一个文件后,第一次对其的写入都会失败。然后说文件被其他进程(w3wp.exe)占用.这是为什么...
问题在 IOUtils.CreateFile(_filePath);
CreateFile 贴码出来
你那个locker既锁了父又锁了子,当然是一直占用着的。
用File已有静态方法写日志,自带线程安全属性,不需要lock