我有一个正在处理数据并为另一个服务导出xml文件的服务,该服务通常处理少量数据(每分钟约5个文件),但有时会丢弃大量数据,并且可能处理需要创建的数据一次全部100个文件。
该服务运行良好,但偶尔会出现错误:
The process cannot access the file 'C:\File.xml' because it is being used by another process.
这很奇怪,因为应该一次性创建,写入和关闭文件,所以我不知道是什么会导致此问题。该问题似乎在重负载下更经常发生,但在轻负载下也经常发生。自然,这在调试时永远不会出现,或者我现在可能已经解决了。
这是实际写入文件的功能:
public bool WriteDocument(Object Data)
{
XmlDocument X = new XmlDocument();
XmlSchemaSet schemaSet = new XmlSchemaSet();
schemaSet.Add(null, "Schema.xsd");
X.Schemas = schemaSet;
if (!Directory.Exists("OutputDirectory"))
{
Directory.CreateDirectory("OutputDirectory");
}
string File = Path.Combine("OutputDirectory", @"File" + ".xml");
XmlSerializer Encoder = new XmlSerializer(typeof(Object));
//Do stuff to data object to prepare for output
using (MemoryStream buffer = new MemoryStream())
{
Encoder.Serialize(buffer, Data);
buffer.Position = 0;
X.Load(buffer);
X.Validate((sender, e) =>
{
if (e.Severity == XmlSeverityType.Error)
{
result = false;
}
else
{
result = true;
}
});
}
if (result)
{
while (System.IO.File.Exists(File))
{
File = MakeUniqueName(File);
}
XmlWriterSettings settings = new XmlWriterSettings();
settings.Encoding = Encoding.UTF8;
using (XmlWriter Writer = XmlWriter.Create(File, settings))
{
X.WriteTo(Writer);
Writer.Close();
}
}
return result;
}