1

I am getting this error when multiple user reads the key at the same time , an error occurred loading a configuration file:

The process cannot access file file 'web.config' becuase it is being used by another process

I am using like below in code.

var value = ConfigurationManager.GetSection("keyname") as NameValueCollection;
umadik
  • 101
  • 2
  • 17
Sagar Jena
  • 51
  • 5
  • Configuration config = ConfigurationManager.OpenExeConfiguration(string.Empty); this line is causing the issue after debugging got to know – Sagar Jena Nov 13 '21 at 17:41

1 Answers1

0

If you have concurrent read from web.config I suggest you to use ReadWriterLock Class.

In your Class use:

  static ReaderWriterLock rwl = new ReaderWriterLock();
  ....
  rwl.AcquireReaderLock();
  try {
        // It is safe for this thread to read from the shared resource.
        var value = ConfigurationManager.GetSection("keyname") as NameValueCollection;
     }
     finally {
        // Ensure that the lock is released.
        rwl.ReleaseReaderLock();
     }

Documentation https://learn.microsoft.com/en-us/dotnet/api/system.threading.readerwriterlock?view=net-5.0

Alex
  • 9
  • 5
  • Please read this also https://stackoverflow.com/questions/745384/thread-safe-usage-of-system-configuration thanks – Alex Nov 12 '21 at 08:06
  • From the link, static methods are thread safe and instance methods are not. Since `GetSection` is static, it is safe, and since the object returned from it is assigned to a local variable, it does not seem to be shared across threads. What seems more likely is that the file is [in use by some other process](https://stackoverflow.com/questions/13477557/unable-to-load-configuration-file-web-config-in-use-by-another-process), or by [Visual Studio](https://stackoverflow.com/questions/50714723/the-process-cannot-access-the-file-web-config-because-it-is-being-used-by-anothe?rq=1). – John Wu Nov 12 '21 at 17:22
  • Configuration config = ConfigurationManager.OpenExeConfiguration(string.Empty); this line causing the issue – Sagar Jena Nov 13 '21 at 17:41