欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

C# -- 多线程向同一文件写入

程序员文章站 2022-06-05 19:23:18
1. 多线程向同一文件写入Log. ......

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); } }