1. 多线程向同一文件写入log.
public delegate void asynclog(string str1, string str2);
private void test() { console.writeline("test start..."); for (int i = 0; i < 100; i++) { asynclog asylog1 = new asynclog(writelog); asylog1.begininvoke("eventactiona" + i.tostring(), "eventcontenta" + i.tostring(), null, null); asynclog asylog2 = new asynclog(writelog); asylog2.begininvoke("eventactionb" + i.tostring(), "eventcontentb" + i.tostring(), null, null); asynclog asylog3 = new asynclog(writelog); asylog3.begininvoke("eventactionc" + i.tostring(), "eventcontentc" + i.tostring(), null, null); } console.writeline("test end..."); }
public static object lockobject = new object();
private void writelog(string streventtype, string streventcontent) { lock (lockobject) { console.writeline("write log start... threadid:{0}", thread.currentthread.managedthreadid); string strlogpath = string.format("d:\\log\\log{0}.log", datetime.now.tostring("yyyy-mm-dd")); if (!file.exists(strlogpath)) { file.create(strlogpath).close(); } filestream fs = new filestream(strlogpath, filemode.append, fileaccess.write); streamwriter sw = new streamwriter(fs, encoding.utf8); sw.writeline(string.format("{0} {1}", streventtype, streventcontent)); sw.close(); fs.close(); console.writeline("write log end threadid:{0}", thread.currentthread.managedthreadid); } }
您可能感兴趣的文章:
如您对本文有疑问或者有任何想说的,请 点击进行留言回复,万千网友为您解惑!
网友评论