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