Skip to main content
 首页 » 编程设计

c#之多线程锁和监视器类不起作用

2024年01月13日31me-sa

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

我锁定了允许读取或写入的整个函数,但我仍然会遇到错误,例如 该进程无法访问文件“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 
} 

请您参考如下方法:

您正在创建一个新 监视器以在每次调用该属性时锁定。您需要锁定同一个监视器,否则锁定根本没有意义。

您还应该只使用“锁定”语句 - 您永远不会等待,因此脉冲没有意义。目前,如果抛出任何异常,您最终将“泄漏”锁。这通常是一个非常糟糕的问题,但由于您无论如何都没有重复使用锁,所以这掩盖了问题。

例如:

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; 
        } 
    } 
} 

顺便说一句,这看起来比我在一个属性中真正期望的要多。您确定一种方法不会更有意义吗?