【发布时间】:2016-04-15 04:55:57
【问题描述】:
我创建了一个 webservice(.asmx),它在每个页面的页面加载事件中使用 ajax 调用。它基本上是用来记录网站用户行为的。我正在将此捕获的信息序列化为一个 xml 文件。这是我使用的方法。
public static void SerializeObject<T>(T serializableObject, string fileName)
{
if (serializableObject == null) { return; }
try
{
XmlDocument xmlDocument = new XmlDocument();
XmlSerializer serializer = new XmlSerializer(serializableObject.GetType());
using (MemoryStream stream = new MemoryStream())
{
serializer.Serialize(stream, serializableObject);
stream.Position = 0;
xmlDocument.Load(stream);
xmlDocument.Save(fileName);
stream.Close();
}
}
catch (Exception ex)
{
//Log exception here
}
}
public static T DeSerializeObject<T>(string fileName)
{
if (string.IsNullOrEmpty(fileName)) { return default(T); }
T objectOut = default(T);
try
{
XmlDocument xmlDocument = new XmlDocument();
xmlDocument.Load(fileName);
string xmlString = xmlDocument.OuterXml;
using (StringReader read = new StringReader(xmlString))
{
Type outType = typeof(T);
XmlSerializer serializer = new XmlSerializer(outType);
using (XmlReader reader = new XmlTextReader(read))
{
objectOut = (T)serializer.Deserialize(reader);
reader.Close();
}
read.Close();
}
}
catch (Exception ex)
{
//Log exception here
}
return objectOut;
}
public static List<UserPath> saveandfetch<T>(string sord, string filename, T serializableObject=default(T))
{
lock (locker)
{
if (sord == "S")
{
List<UserPath> up = serializableObject as List<UserPath>;
SerializeObject<List<UserPath>>(up, filename);
return null;
}
else if (sord == "D")
{
List<UserPath> up = DeSerializeObject<List<UserPath>>(filename);
return up;
}
else
{
return null;
}
}
}
第三个函数用于通过调用正确的函数来序列化和反序列化。我已经在这个函数上加了一个锁。但问题是,即使在此之后,当两个或多个用户同时浏览时,数据也会被覆盖。
我这样调用函数:
List<UserPath> UPL = saveandfetch<List<UserPath>>("D",Server.MapPath("/UserPath.xml"));//deserialize
saveandfetch<List<UserPath>>("S",Server.MapPath("/UserPath.xml"),UPL); //serialize
我做错了什么?
【问题讨论】:
-
储物柜是'Object'类型的静态对象吗?
-
不,它不是静态对象。
标签: asp.net web-services serialization concurrency locking