我有一个简单的页面,它从文件系统加载 XML,填充文本框,这些可以更新和保存。对于序列化和反序列化,我使用这些方法:
private static readonly object FormDataLock = new object();
public static FormData getFormData(string filename)
{
FormData fd;
lock (FormDataLock)
{
XmlSerializer x = new XmlSerializer(typeof(FormData));
using (Stream s = new FileStream(filename, FileMode.Open, FileAccess.Read))
{
return (FormData)x.Deserialize(s);
}
}
}
public void saveFormData(string filename)
{
lock (FormDataLock)
{
XmlSerializer x = new XmlSerializer(typeof(FormData));
using (Stream s = new FileStream(filename, FileMode.Create, FileAccess.Write))
{
x.Serialize(s, this);
}
}
}
但问题是,我有时会遇到问题(当我在 PageLoad 之后单击“保存”按钮太快时我注意到了)IOException:
IOException: The process cannot access the file ".." because it is being used by another process.
我试图用互斥锁锁定块,但它仍然无法正常工作。页面表单非常简单,但我在上面使用了 UpdatePanel(重要吗?)。
当页面加载完成并且第一次保存请求完成后,我可以尽可能快地单击按钮,一切正常(没有例外)。