1

我正在尝试执行以下操作:

var path = Server.MapPath("File.js"));

// Create the file if it doesn't exist or if the application has been restarted
// and the file was created before the application restarted
if (!File.Exists(path) || ApplicationStartTime > File.GetLastWriteTimeUtc(path)) {
    var script = "...";

    using (var sw = File.CreateText(path)) {
        sw.Write(script);
    }
}

但是有时有时会抛出以下错误:

该进程无法访问文件“...\File.js”,因为它正被另一个进程使用

我在这里看过类似的问题,但我的似乎与其他问题略有不同。此外,在服务器负载过重之前我无法复制它,因此我希望在上传修复程序之前确保它是正确的。

如果有人能告诉我如何解决这个问题,我将不胜感激。

谢谢

4

1 回答 1

2

听起来两个请求同时在您的服务器上运行,并且它们都试图同时写入该文件。

您需要添加某种锁定行为,或者编写更健壮的架构。在不了解更多关于您实际尝试使用此文件写入过程完成的具体内容的情况下,我能建议的最好方法是锁定。我通常不喜欢在 Web 服务器上进行这样的锁定,因为它使请求相互依赖,但这可以解决问题。


编辑:Dirk 在下面指出,这可能会或可能不会真正起作用。根据您的 Web 服务器配置,可能不会共享静态实例,并且可能会出现相同的结果。我提供了这个作为概念证明,但你绝对应该解决根本问题。


private static object lockObj = new object();

private void YourMethod()
{
    var path = Server.MapPath("File.js"));

    lock (lockObj)
    {
        // Create the file if it doesn't exist or if the application has been restarted
        // and the file was created before the application restarted
        if (!File.Exists(path) || ApplicationStartTime > File.GetLastWriteTimeUtc(path))
        {
            var script = "...";

            using (var sw = File.CreateText(path))
            {
                sw.Write(script);
            }
        }
    }
}

但是,再一次,我很想重新考虑你实际上想用这个来完成什么。也许你可以在方法中构建这个文件Application_Start,甚至只是一个静态构造函数。对每个请求都这样做是一种混乱的方法,可能会导致问题。特别是在重负载下,每个请求都将被迫同步运行。

于 2015-01-15T09:15:44.763 回答