简体   繁体   中英

IO exception while reading/writing to file

I am using an XML file to store the values. This XML file can be accessed from multiple methods.

Private object lockObject = new object()

Method1
{
   Lock(this.lockObject)
   {
     MyCommonMethod()
   }
}

Timer.ElapseEvent
{
   Lock(this.lockObject)
   {
     MyCommonMethod()
   }
}

MyCommonMethod()
{
  // Read/Write to XML file.
  var element = XElement.Load(path);
  // some operations

   element.save(path)
}

This class is used by many other classes and some times it throws System.IO exception, the file is already used by other process , although I have used the lock statement

Please guide.

如果您需要在多个类的实例中保持安全,则需要将私有锁定变量设置为static

private static object lockObject = new object();

Remove all calls to Lock and try to change your code like this:

    private void MyCommonMethod()
    {
        lock (this.lockObject)
        {
            var element = XElement.Load(path);
            // some operations
            element.save(path);
        }
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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