===== System.IO.File.AppendAllText 多线程下有点不靠谱 啊,====
以下代码都是asp.net,我能预见到,如果多个客户端并发访问下面这个页面,asp.net从线程池中分配一个空闲的线程去服务这个请求。也就是可能存在多个线程并发访问log.txt文件。
protected void Page_Load(object sender, EventArgs e) { string path = Server.MapPath("~/log.txt"); for (int i = 0; i < 100000; i++) { System.IO.File.AppendAllText(path, i.ToString()); } }
object locker = new object(); protected void Page_Load(object sender, EventArgs e) { string path = Server.MapPath("~/log.txt"); lock (locker) { for (int i = 0; i < 100000; i++) { System.IO.File.AppendAllText(path, i.ToString()); } } }
protected void Page_Load(object sender, EventArgs e) { string path = Server.MapPath("~/log.txt"); System.Threading.ReaderWriterLock rwl = new System.Threading.ReaderWriterLock(); rwl.AcquireWriterLock(1000); for (int i = 0; i < 100000; i++) { System.IO.File.AppendAllText(path, i.ToString()); } rwl.ReleaseWriterLock(); }