我目前正在开发一个项目,该项目有一个外部网站将xml数据发布到我们网站上的指定网址。我最初的想法是首先将xml数据保存到我们服务器上的物理文件作为备份。然后我将数据插入缓存中,从那时起,所有对数据的请求都将被发送到缓存而不是物理文件。
目前我有以下内容:
[HttpPost]
public void MyHandler()
{
// filePath = path to my xml file
// Delete the previous file
if (File.Exists(filePath))
File.Delete(filePath));
using (Stream output = File.OpenWrite(filePath))
using (Stream input = request.InputStream)
{
input.CopyTo(output);
}
// Deserialize and save the data to the cache
var xml = new XmlTextReader(filePath);
var serializer = new XmlSerializer(typeof(MyClass));
var myClass = (MyClass)serializer.Deserialize(xml);
HttpContext.Current.Cache.Insert(myKey,
myClass,
null,
myTimespan,
Cache.NoSlidingExpiration,
CacheItemPriority.Default, null);
}
我遇到的问题是,我总是会抛出异常,因为当我尝试第二篇帖子来更新数据时,我正在保存的文件“正在使用”。
一位同事建议在我星期五离开工作之前使用Mutex课程,所以我想知道这是否是正确的方法?
基本上我只是想要理智地检查这是管理数据的好方法吗?我可以看到显然存在如何将数据写入文件的问题,但除此之外,我的方法是否有意义?
由于