0
我有一個文件夾存在於其中有很多XML文件的文件系統上。比方說10,000。多個當前請求到文件系統文件夾處理文件C#XML
我有多個(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 – aherrick
您可以通過單一中央服務同步服務。通過一箇中央服務,你可以防止不同的服務並行訪問同一個文件。或者,您可以確定性地將這些文件分成一些外部集,並將它們分配給不同的服務。 – MaMazav