我有一个GetServiceMap()方法,它调用反序列化器然后打开流并从中读取内容。
问题是我有一个GetAllGroups()方法也在同一个流上调用反序列化器。
我如何同步它?使用ManualResetEvent可能吗?
public ServiceMapModel GetServiceMap()
{
s._mre.WaitOne();
return s.Deserialize();
}
public List<Group> GetAllGroups()
{
s._mre.WaitOne();
return s.Deserialize().Groups;
}
反序列化方法:
public ManualResetEvent _mre = new ManualResetEvent(true);
public ServiceMapModel Deserialize()
{
_serviceMap = new ServiceMapModel();
_mre.Reset();
try
{
using (var fileStream = new FileStream(Settings.Path, FileMode.Open))
{
XmlReaderSettings settings = new XmlReaderSettings();
settings.IgnoreComments = true;
using (XmlReader reader = XmlReader.Create(fileStream, settings))
{
_serviceMap = _serializer.Deserialize(reader) as ServiceMapModel;
}
fileStream.Close();
}
}
catch (IOException)
{
}
_mre.Set();
return _serviceMap;
}