예제 #1
0
                public void FlushChanges()
                {
                    Tuple <long, byte[]>[] changed;

                    lock (_snapshots.SyncRoot)
                    {
                        if (!_resetFile)
                        {
                            if (_dirtyKeys.Count == 0)
                            {
                                return;
                            }

                            changed = _dirtyKeys.Select(key =>
                            {
                                var buffer = _serializer.Serialize(_version, _snapshots[key]);

                                if (!_offsets.TryGetValue(key, out var offset))
                                {
                                    offset = _currOffset;
                                    _offsets.Add(key, offset);
                                    _currOffset += _bufSizeLen + buffer.Length;
                                }

                                return(Tuple.Create(offset, buffer));
                            }).OrderBy(t => t.Item1).ToArray();
                        }
                        else
                        {
                            _offsets.Clear();
                            _currOffset = _versionLen;

                            changed = _snapshots.Select(pair =>
                            {
                                var buffer = _serializer.Serialize(_version, pair.Value);

                                var offset = _currOffset;
                                _offsets.Add(pair.Key, offset);
                                _currOffset += _bufSizeLen + buffer.Length;

                                return(Tuple.Create(offset, buffer));
                            }).OrderBy(t => t.Item1).ToArray();
                        }

                        _dirtyKeys.Clear();
                    }

                    Debug.WriteLine($"Snapshot (Save): {_fileName}");

                    Directory.CreateDirectory(Path.GetDirectoryName(_fileName));

                    using (var stream = File.OpenWrite(_fileName))
                    {
                        if (stream.Length == 0)
                        {
                            stream.WriteByte((byte)_version.Major);
                            stream.WriteByte((byte)_version.Minor);
                        }

                        foreach (var tuple in changed)
                        {
                            stream.Seek(tuple.Item1, SeekOrigin.Begin);
                            stream.Write(tuple.Item2);
                        }
                    }
                }