当前位置: 移动技术网 > IT编程>开发语言>c# > C# -- 多线程向同一文件写入

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

2019年09月20日  | 移动技术网IT编程  | 我要评论
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); } }

 

如您对本文有疑问或者有任何想说的,请 点击进行留言回复,万千网友为您解惑!

相关文章:

验证码:
移动技术网