简体   繁体   English

检查文件是否被可执行运行的其他实例使用

[英]Check If File Is In Use By Other Instances of Executable Run

Before I go into too detail, my program is written in Visual Studio 2010 using C# .Net 4.0. 在我太详细之前,我的程序是使用C#.Net 4.0在Visual Studio 2010中编写的。

I wrote a program that will generate separate log files for each run. 我编写了一个程序,该程序将为每次运行生成单独的日志文件。 The log file is named after the time, and accurate up at millisecond (for example, 20130726103042375.log ). 日志文件以时间命名,并且精确到毫秒(例如20130726103042375.log )。 The program will also generate a master log file for the day if it has not already exist (for example, *20130726_Master.log*) 如果该程序尚不存在,该程序还将为其生成当天的主日志文件(例如* 20130726_Master.log *)

At the end of each run, I want to append the log file to a master log file. 在每次运行结束时,我想将日志文件追加到主日志文件中。 Is there a way to check if I can append successfully? 有没有办法检查我是否可以成功追加? And retry after Sleep for like a second or something? 并在“ Sleep ”后重试一秒钟左右?

Basically, I have 1 executable, and multiple users (let's say there are 5 users). 基本上,我有1个可执行文件,并且有多个用户(假设有5个用户)。

All 5 users will access and run this executable at the same time. 所有5个用户将同时访问和运行此可执行文件。 Since it's nearly impossible for all user to start at the exact same time (up to millisecond), there will be no problem generate individual log files. 由于几乎所有用户都不可能在同一时间(最多毫秒)启动,因此生成单个日志文件不会有问题。

However, the issue comes in when I attempt to merge those log files to the master log file. 但是,当我尝试将那些日志文件合并到主日志文件时,就会出现问题。 Though it is unlikely, I think the program will crash if multiple users are appending to the same master log file. 虽然不太可能,但我认为如果有多个用户附加到同一主日志文件,则该程序将崩溃。

The method I use is 我使用的方法是

File.AppendAllText(masterLogFile, File.ReadAllText(individualLogFile));

I have check into the lock object, but I think it doesn't work in my case, as there are multiple instances running instead of multiple threads in one instance. 我已经检查了lock对象,但是我认为这种情况不起作用,因为有多个实例在运行,而不是在一个实例中运行多个线程。

Another way I look into is try/catch , something like this 我研究的另一种方式是try/catch ,像这样

try
{
    stream = file.Open(FileMode.Open, FileAccess.ReadWrite, FileShare.None);
}
catch {}

But I don't think this solve the problem, because the status of the masterLogFile can change in that brief millisecond. 但是我认为这不能解决问题,因为masterLogFile的状态可以在短时间内改变。

So my overall question is: Is there a way to append to masterLogFile if it's not in use, and retry after a short timeout if it is? 因此,我的总体问题是:是否有一种方法可以在未使用masterLogFile的情况下追加它,并在短时超时后重试? Or if there is an alternative way to create the masterLogFile? 还是如果有其他方法可以创建masterLogFile?

Thank you in advance, and sorry for the long message. 在此先感谢您,很长的信息对不起。 I want to make sure I get my message across and explain what I've tried or look into so we are not wasting anyone's time. 我想确保我能传达我的信息并解释我尝试过或研究过的内容,以免浪费任何人的时间。

Please let me know if there's anymore information I can provide to help you help me. 如果有更多信息可以帮助您,请告诉我。

Your try/catch is the way to do things. 尝试/捕获是做事的方式。 If the call to File.Open succeeds, then you can write to to the file. 如果对File.Open的调用成功,则可以写入文件。 The idea is to keep the file open. 想法是保持文件打开。 I would suggest something like: 我建议类似的东西:

bool openSuccessful = false;
while (!openSuccessful)
{
    try
    {
        using (var writer = new StreamWriter(masterlog, true)) // append
        {
            // successfully opened file
            openSuccessful = true;
            try
            {
                foreach (var line in File.ReadLines(individualLogFile))
                {
                    writer.WriteLine(line);
                }
            }
            catch (exceptions that occur while writing)
            {
                // something unexpected happened.
                // handle the error and exit the loop.
                break;
            }
        }
    }
    catch (exceptions that occur when trying to open the file)
    {
        // couldn't open the file.
        // If the exception is because it's opened in another process,
        // then delay and retry.
        // Otherwise exit.
        Sleep(1000);
    }
}
if (!openSuccessful)
{
    // notify of error
}

So if you fail to open the file, you sleep and try again. 因此,如果无法打开文件,则请休眠并重试。

See my blog post, File.Exists is only a snapshot , for a little more detail. 请参阅我的博客文章File.Exists仅是快照 ,以获取更多详细信息。

I would do something along the lines of this as I think in incurs the least overhead. 我会按照这种方式做一些事情,因为我认为这样可以减少开销。 Try/catch is going to generate a stack trace(which could take a whole second) if an exception is thrown. 如果抛出异常,try / catch将生成堆栈跟踪(可能需要一整秒钟)。 There has to be a better way to do this atomically still. 必须有一种更好的方法来自动执行此操作。 If I find one I'll post it. 如果找到一个,我将其发布。

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

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