繁体   English   中英

对文件系统文件夹的多个当前请求以处理文件C#XML

[英]Multiple Current Requests to File System folder to Process Files C# XML

我有一个文件系统上存在的文件夹,其中有很多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
            }
        }
    }
}

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

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

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

暂无
暂无

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

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