简体   繁体   English

可以记录到ASP.net WEb服务器中的文本文件导致锁定

[英]Can logging to text file in ASP.net WEb server cause locks

Can logging to text file in ASP.net WEb server cause locks 可以记录到ASP.net WEb服务器中的文本文件导致锁定

Thi is my code: 这是我的代码:

var outStream = new FileStream(Server.MapPath("~\\bin\\error.txt"), FileMode.Append, FileAccess.Write, FileShare.ReadWrite);

As you see FileShare is both read and write. 如您所见, FileShare是可读写的。

So far I have not seen any issues. 到目前为止,我还没有看到任何问题。 Are you aware of possible issues using this method. 您是否知道使用此方法可能出现的问题。 (I do not want to log error to windows event) (我不想将错误记录到Windows事件中)

Not 100% sure I understand what you are asking, but any time something writes to a file, the file is locked by that application for the period of time that it takes to complete the write. 不能100%地确定我理解您的要求,但是每当有文件写入文件时,该文件就会在完成写入过程中被该应用程序锁定。 If there is another application writing to the same file at times, there will be the potential for conflict. 如果有时另一个应用程序正在写入同一文件,则可能会发生冲突。 If both applications are coded to handle conflicts of this nature, then all will be fine. 如果两个应用程序都经过编码以处理这种性质的冲突,那么一切都会很好。 So if you are coding to handle this situation, you would put the write method in a TRY block within a WHILE block. 因此,如果您正在编码以处理这种情况,则可以将write方法放在WHILE块内的TRY块中。 If an error occurs writing, then it would stay in the while block and pause for a second or something and then try again. 如果在写入时发生错误,则它将停留在while块中并暂停一秒钟左右,然后重试。 Once the write is successful, break out of the while block. 一旦写入成功,就退出while块。 You may also want to put in a counter and limit the number of tries. 您可能还想放入柜台并限制尝试次数。

Just be aware that if you do this that the thread will sit here until the write is successful, so if you don't want this to hold up your application it needs to be done with another thread. 请注意,如果执行此操作,则该线程将一直位于此处,直到写入成功为止,因此,如果您不希望此操作阻止您的应用程序,则需要使用另一个线程来完成。

I think you would just want to do a lock on a static object that wraps the File I/O. 我认为您只想对包装文件I / O的静态对象进行锁定。 This static object would ensure the file updates are thread safe. 该静态对象将确保文件更新是线程安全的。

With respect to Mr. Hinkle, I had always heard one would not want to have multiple try/catch fails inside a while loop as pure design -- unless I'm missing something. 关于欣克尔先生,我一直听说人们不希望在while循环内将多次try / catch失败视为纯粹的设计-除非我错过了一些东西。 I can see where practically this would work, but I always thought exceptions should not become part of the "main flow" in this way. 我可以看到这实际上在什么地方可行,但是我一直认为例外不应以这种方式成为“主流”的一部分。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM