我正在使用 XML 来模拟数据库,并且在使用虚拟数据加载它时,我不断收到错误消息,告诉我有多个根元素。打开文件后,我可以确认多个根元素正在写入文件,但除了简单地同步调用进程之外,我所做的一切似乎都无法阻止它这样做。
这是我的代码示例:
// Check to see if the file is available. If it is, parse it. Otherwise create
// a new root element. Done in the constructor since the XElement is used in
// multiple locations.
public CourseXmlWriter()
{
if (!File.Exists(Settings.Default.DataDirectory + Settings.Default.AltDb))
{
_courses = new XElement("Courses");
}
else
{
var attempts = 0;
while (attempts < MaxAttempts)
{
try
{
using (var stream = new FileStream(_dataFile,
FileMode.OpenOrCreate, FileAccess.Read, FileShare.None))
{
_courses = XElement.Load(stream);
}
break;
}
catch (IOException)
{
Thread.Sleep(1000);
attempts++;
}
}
}
}
对于初始加载,我只是尝试读取文件以便对其进行解析,因此我限制了它的访问。我还确保在解析它时没有人可以访问它。我会尝试一段时间,然后继续并完全拒绝该请求。
然后,当尝试将信息写入文件时,我正在执行以下操作:
var attempts = 0;
while (attempts < MaxAttempts)
{
try
{
using (var stream = new FileStream(_dataFile,
FileMode.OpenOrCreate, FileAccess.Write, FileShare.None))
{
_courses.Save(stream);
}
break;
}
catch (IOException)
{
attempts++;
Thread.Sleep(1000);
}
}
同样,这是异步运行的,我可以在它崩溃之前成功写入一些 (15-150) 记录,There are multiple root elements. Line 15, position 6.
其中位置和行是可变的。
以下是异步调用和回调:
来电:
for (var i = 0; i < coursesToGenerate; i++)
{
var request = new CreateCourseRequest
{
Description = Path.GetRandomFileName().Replace(".", ""),
Name = Path.GetRandomFileName().Replace(".", "")
};
Func<CreateCourseRequest, CreateCourseResponse> func =
_courseAgent.CreateCourse;
func.BeginInvoke(request, CreateCourseComplete, func);
}
回调:
private void CreateCourseComplete(IAsyncResult ar)
{
var caller = (Func<CreateCourseRequest, CreateCourseResponse>) ar.AsyncState;
var result = caller.EndInvoke(ar);
if (result.Status == ResponseBase.ResponseStatus.Successful)
{
_successful++;
}
}
有什么想法吗?