试了很多种方法,共享锁也试了,最终还是这个方法利用线程池来解决的
private static object o = new object();
if (!Directory.Exists(AppDomain.CurrentDomain.BaseDirectory +"log"))
{
Directory.CreateDirectory(AppDomain.CurrentDomain.BaseDirectory + "log");
}
logPath= AppDomain.CurrentDomain.BaseDirectory + "log\\"+DateTime.Today.ToString("yyyy-MM-dd")+".log";
if (!File.Exists(logPath))
{
using (var sw = new StreamWriter(logPath, true))
{
}
}
ThreadPool.QueueUserWorkItem(new WaitCallback(obj =>//线程池,在有线程池线程变得可用时执行
{
lock (o)
{
using (var sw = new StreamWriter(logPath, true))
{
var sb = new StringBuilder();