簡體   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