多线程锁和监视器类无法正常工作

use*_*657 1 c# multithreading locking class monitor

我有一个读取和写入的文件.我需要确保在写入时,没有其他人会尝试写入它.

我对整个函数进行了锁定,允许读取或写入,但仍然会出现错误,例如进程无法访问文件'FILENAME',因为它正由另一个进程使用.

public static TYPE Property{

get{
    data mydata;
    Object obj = new object();
    Monitor.Enter(obj);

    // check if data has not changed
    // if it has not, just read

    using (Stream stream = File.Open(fileLocation, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) {
        //....
    }
    // else, if data changed, then need to write to  file to save the new data

    using (Stream stream = File.Open(fileLocation, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.Read)) {
        BinaryFormatter bf = new BinaryFormatter();

        try {
            bf.Serialize(stream, (data);
        }
        //DONE processing

        Monitor.Pulse(obj);
        Monitor.Exit(obj);
        return data
}
Run Code Online (Sandbox Code Playgroud)

Jon*_*eet 10

您每次调用属性时都要创建一个新的监视器来锁定.您需要锁定同一台显示器,否则根本没有锁定点.

你也应该只使用一个"锁定"声明 - 你永远不会等待,所以脉冲没有意义.目前,如果抛出任何异常,您最终会"泄漏"锁定.这通常是一个非常糟糕的问题,但是因为你还没有重新使用锁,这就是掩盖了这个问题.

例如:

private static readonly object monitor = new object();

public static TYPE Property
{
    get
    {
        lock(monitor)
        {
            // check if data has not changed
            // if it has not, just read
            using (Stream stream = File.Open(fileLocation, 
                   FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
            {
                ....
            }
            // else, if data changed, then need to write to 
            // file to save the new data
            using (Stream stream = File.Open
                       (fileLocation, FileMode.OpenOrCreate,
                        FileAccess.ReadWrite, FileShare.Read))
            {
                BinaryFormatter bf = new BinaryFormatter();
                bf.Serialize(stream, data);
            }
            return data;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

顺便说一句,这似乎比我在房产中所期望的更多.你确定一种方法不会更有意义吗?