0

我有一个存在于文件系统中的文件夹,其中包含大量 XML 文件。假设是 10,000。

我有多个 (5) Windows 服务每 30 秒检查一次该文件夹并同时处理文件。我正在尝试编写足够智能的服务进程代码,以便它可以处理并发请求以进行处理。

然而,它有时会挂在几个文件上。

E[The process cannot access the file '...' because it is being used by another process.]

我看到上面的错误在处理过程中记录了大约 1% 的文件。我可以做些什么来改进以下代码以防止这种情况发生?

class Program
{
    private static string _instanceGuid;
    static string InstanceGuid
    {
        get
        {
            if(_instanceGuid == null)
            {
                _instanceGuid =  Guid.NewGuid().ToString();
            }
            return _instanceGuid;
        }
    }

    static void Main(string[] args)
    {
        string[] sourceFiles = Directory.GetFiles("c\\temp\\source\\*.xml")
                                       .OrderBy(d => new FileInfo(d).CreationTime).ToArray();

        foreach (string file in sourceFiles)
        {
            var newFileName = string.Empty;

            try
            {
                // first we'll rename in this way try and 
                // i would think it should throw an exception and move on to the next file. an exception being thrown means that file should already be processing by another service. 

                newFileName = string.Format("{0}.{1}", file, InstanceGuid);
                File.Move(file, newFileName);

                var xml = string.Empty;
                using (var s = new FileStream(newFileName, FileMode.Open, FileAccess.Read, FileShare.None))
                using (var tr = new StreamReader(s))
                {
                    xml = tr.ReadToEnd();
                }

                // at this point we have a valid XML save to db
            }
            catch (FileNotFoundException ex)
            {
                // continue onto next source file
            }
            catch (Exception ex)
            {
                // log error
            }
        }
    }
}
4

1 回答 1

0

在以下行将“FileShare.None”替换为“FileShare.Read”:

            using (var s = new FileStream(newFileName, FileMode.Open, FileAccess.Read, FileShare.None))

http://msdn.microsoft.com/en-us/library/system.io.fileshare%28v=vs.110%29.aspx

于 2013-11-14T21:50:39.190 回答