Search code examples
c#.netmultithreadingmanualresetevent

Reading twice from FileStream


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;
    }

Solution

  • 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.