1

I have a GetServiceMap() method which calls deserializer who then opens the stream and reads something from it.

The problem is that i have a GetAllGroups() method also who calls deserializer over the same stream.

How would i syncronize it? With ManualResetEvent maybe?

public ServiceMapModel GetServiceMap()
    {
        s._mre.WaitOne();
        return s.Deserialize();
    }

public List<Group> GetAllGroups()
    {
        s._mre.WaitOne();
        return s.Deserialize().Groups;
    }

Deserialize method:

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;
    }
Alexei Levenkov
  • 98,904
  • 14
  • 127
  • 179
Bip
  • 893
  • 5
  • 14
  • 29

1 Answers1

2

For your case basic lock should be enough - no reason to use more complicated objects.

I would actually cache result of deserialization instead of reading from file every time, but it is your call.

Alexei Levenkov
  • 98,904
  • 14
  • 127
  • 179
  • How would you cache it? Could you provide a bit of code please? :) I mean, you suggest actually to load entire file to memory stream and then write/read from it. when will be the right moment to save it to file? :) – Bip Mar 15 '12 at 00:23
  • 1
    `private ServiceMapModel cache;` then assign the return value to that and use the cached value instead rereading from file – zapl Mar 15 '12 at 00:49