我在一个应用程序中使用C#,文件被锁定时遇到了一些问题。
这段代码做到了这一点,
while (true)
{
Read a packet from a socket (with data in it to add to the file)
Open a file // one of these randomly throws an exception saying that the file is locked
Writes data to it
Close a file
} 但在此过程中,文件会被锁定。我真的不明白我们是如何捕获和报告异常的,所以我不明白为什么文件不会每次都被关闭。
我最好的猜测是有别的东西在打开这个文件。它不太可能是另一个应用程序,但它可能是一个不同的主题,但我只想证明这一点。有没有人可以提供一段代码来检查文件是否打开,如果打开了,请报告打开了文件的processId和threadId。
例如,如果我有这样的代码,
StreamWriter streamWriter1 = new StreamWriter(@"c:\logs\test.txt");
streamWriter1.WriteLine("Test");
// code to check for locks??
StreamWriter streamWriter2 = new StreamWriter(@"c:\logs\test.txt");
streamWriter1.Close();
streamWriter2.Close();这将抛出一个异常,因为当我们第二次尝试打开该文件时,该文件被锁定。那么,我可以在其中添加什么注释,以报告当前应用程序(进程Id)和当前线程(线程Id)已锁定文件?
谢谢。
发布于 2010-04-21 11:38:25
下面是一些可以跨线程保护资源的伪代码:
while (true)
{
Read a packet from a socket (with data in it to add to the file)
lock (static locker object)
{
Open a file
Writes data to it
Close a file
}
}在C#世界中,静态锁定器对象通常在类级别声明,如下所示:
private static readonly object locker = new object();如果文件打开和关闭之间的语句抛出异常,我还建议使用using关键字来保护文件资源。重做伪代码:
while (true)
{
Read a packet from a socket (with data in it to add to the file)
lock (static locker object)
{
using (Open a file)
{
Writes data to it
} // leaving the using block will close the file
}
}发布于 2010-04-21 10:57:29
这并没有直接回答您的问题,但是像Process Explorer和Process Monitor这样的免费Sysinternals工具对于这种调试非常有用。
https://stackoverflow.com/questions/2679995
复制相似问题