最近开发一小软件,由于经常要记录运行中的一些信息,而程序又涉及多线程,
这样就引发了一新的问题——线程读写文件时由于并发引起的异常。
- public class log
- {
- private static List<String> strErrs = new List<String>();
- /// <summary>
- /// 标记是否在执行写任务
- /// </summary>
- private static int tag = 0;
- /// <summary>
- /// 发生错误的异常记录
- /// </summary>
- /// <param name="Class">类名</param>
- /// <param name="Method">方法名</param>
- /// <param name="Err">错误信息</param>
- public static void WriteErr(String Class, String Method, String Err)
- {
- strErrs.Add("[" + DateTime.Now + "] [" + Class + "] [" + Method + "] [" + Err + "]");
- if (tag++ == 0)
- {
- WriteErr();
- }
- }
- private static void WriteErr()
- {
- StreamWriter sw = null;
- try
- {
- sw = File.AppendText(AppPath + errTxt);
- while (strErrs.Count > 0)
- {
- sw.WriteLine(strErrs[0]);
- sw.WriteLine();
- strErrs.RemoveAt(0);
- }
- sw.Flush();
- sw.Close();
- tag = 0;
- }
- catch (Exception ex)
- {
- throw ex;
- }
- finally
- {
- try
- {
- if (sw != null) sw.Close();
- }
- catch (Exception ex)
- {
- throw ex;
- }
- }
- }
- }
把这段代码写在一类里面,然后只要调用WriteErr方法就可以了