简体   繁体   中英

How to sync access to file between ASP.NET web site and ASP.NET web service on one web server

I have deployed ASP.NET web site and ASP.NET web service on the same web server. Both of them require access to shared file.

How to implement/share lock that supports single writers and multiple readers? If somebody reads, nobody can write, but all still can read. If somebody writes, nobody can read/write.

to open file for writing with allowing other threads to read it use System.IO.File.Open method with System.IO.FileShare.Read. Ie.:

System.IO.File.Open("path.txt",System.IO.FileMode.OpenOrCreate,System.IO.FileAccess.ReadWrite,System.IO.FileShare.Read)

Other (reading) threads should use System.IO.FileAccess.Read

Signature of Open method:

public static FileStream Open(string path, FileMode mode, FileAccess access, FileShare share);

UPDATE If you need all instances to ocasionally write to file. Use Mutex class to reserve file writing. Ie.:

    Mutex mut = new Mutex("filename as mutex name");
    mut.WaitOne();
    //open file for write, 
    //write to file
    //close file
    mut.ReleaseMutex();

Hope it helps.

使用System.Threading命名空间中的ReaderWriterLock或ReaderWriterLockSlim(.NET 2.0)类来处理单个作者/多个读者案例。

Well, you can do something like this:

public class yourPage {
    static object writeLock = new object();
    void WriteFile(...) {
         lock(writeLock) {
              var sw = new StreamWriter(...);
              ... write to file ...
         }
}

Basically, this solution is only good for cases when the file will be opened for writing a short amount of time. You may want to consider caching the file for readers, or writing the file to a temp file, then renaming it to minimize contention on it.

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