简体   繁体   English

如何在一台Web服务器上同步ASP.NET网站和ASP.NET Web服务之间的文件访问

[英]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. 我已经在同一台Web服务器上部署了ASP.NET网站和ASP.NET Web服务。 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. 使用允许System.IO.FileShare.Read的System.IO.File.Open方法打开文件进行写入并允许其他线程读取它。 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 其他(读取)线程应使用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. 使用Mutex类保留文件写入。 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. 您可能要考虑为读者缓存文件,或将文件写入临时文件,然后重命名以最大程度地减少对文件的争用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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