使用单例模式实现日志写入。附代码

单例模式保证一个类仅有一个实例,并提供一个访问的他的全局访问点。

 

由于单例模式和日志类的应用场景很相似,因为文件只能被一个进程打开。

所以使用单例模式获取日志文件的实例对象,避免了一个文件多次被打开造成的异常。

代码写了一下,不知道在实际应用的过程中还有没有问题,如果要使用请先测试一下。

如果有不正确的地方,请高手看过后指出来。谢谢!

 

 1 using System;
 2 using System.Collections.Generic;
 3 using System.IO;
 4 using System.Linq;
 5 using System.Text;
 6 using System.Threading;
 7 using System.Threading.Tasks;
 8 
 9 namespace Singleton
10 {
11     class Program
12     {
13         static void Main(string[] args)
14         {
15             for (int i = 0; i < 10000; i++)
16             {
17                 Thread thr1 = new Thread(new ThreadStart(delegate() { Log.Write("问题A" + i); }));
18                 Thread thr2 = new Thread(new ThreadStart(delegate() { Log.Write("问题B" + i); }));
19                 thr1.Start();
20                 thr2.Start();
21             }
22             Console.Read();
23         }
24     }
25 
26     /// <summary>
27     /// 异常文件单利模式(文件只能有一个进程访问,所以使用单利模式实现)
28     /// </summary>
29     public class LogFile
30     {
31         static FileInfo fi = null;
32         static readonly object syncObject = new object();
33         static string saveName = @"C:\WRITE_LOG.TXT";
34         public static FileInfo Log()
35         {
36             lock (syncObject)
37             {
38                 if (fi == null)
39                 {
40                     fi = new FileInfo(saveName);
41                 }
42             }
43             return fi;
44         }
45     }
46     /// <summary>
47     /// 日志写入类
48     /// </summary>
49     public class Log
50     {
51         static readonly object syncObjectWrite = new object();
52         public static void Write(string strContent)
53         {
54             lock (syncObjectWrite)
55             {
56                 using (StreamWriter writer = LogFile.Log().AppendText())
57                 {
58                     writer.WriteLine("=====================================\r\n"
59                         + "添加日期为:" + DateTime.Now.ToString() + "\r\n"
60                         + "日志内容为:" + strContent + "\r\n"
61                         + "=====================================");
62                 }
63             }
64         }
65     }
66 
67 }

 

 

 

  

posted @ 2016-03-18 17:36  Vincent_void  阅读(2386)  评论(0编辑  收藏  举报