“StreamWriter.WriteLine()”函数需要“lock()”吗? [英] Do the “StreamWriter.WriteLine()” function need to “lock()”?

查看:107
本文介绍了“StreamWriter.WriteLine()”函数需要“lock()”吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



我开发了一个写日志的类。它用StreamWriter.WriteLine()函数写。



logStream.WriteLine(msgWrite);

logStream.Flush();



一些不同的线程使用这个类来编写日志,在一个文本文件中(日志文件对所有线程都是通用的)它需要lock()函数吗? />


我应该更改我的代码吗?



lock(syncObj)

{

logStream.WriteLine(msgWrite);

logStream.Flush();

}



请帮帮我。

解决方案

是的它需要锁定,



如何写入数据一个流:



Stream是一个指针,当我们将数据写入文件流时,它会保存一些内存数据首先会存储到缓冲区中然后刷新到内存中如果两个或多个线程同时工作,那么缓冲区可能会被新数据替换,并且您的文件数据可能显示混合线。

因为bu ffer将根据需求进行更改,并且不能确保数据正确写入文件或不仅仅是一个中间数据持有者。



现在锁定将会发挥作用提供文件指针的同步访问,直到一个线程释放该缓冲区或在该流上完成作业,其他人将等待,以便不会发生数据损坏。



快乐编码。 ..

Hi,
i develop a class to write logs. it writes with "StreamWriter.WriteLine()" function.

logStream.WriteLine(msgWrite);
logStream.Flush();

some different threads use this class to write logs, in one text file(The log file is common for all threads) do it need to lock() function?

should i change my code?

lock(syncObj)
{
logStream.WriteLine(msgWrite);
logStream.Flush();
}

please help me.

解决方案

Yes it needs lock,

How a data write to a stream :

Stream is a pointer which holds some memory now when we write data to file stream data would first store into buffer and then flush to your memory now in between that if two or more threads are working simultaneously then buffer may be replaced by the new data and your file data may show mixed lines.
Because buffer will change on demand and it dose not ensure the data is properly written to the file or not its just a intermediate data holder.

Now lock will come to play for providing synchronized access of file pointers until one thread release the that buffer or complete job on that stream other will wait so there is no data damaged will occur.

Happy Coding...


这篇关于“StreamWriter.WriteLine()”函数需要“lock()”吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆