为什么我的流在我自己做之前解锁了?

时间:2018-04-18 12:28:08

标签: c# .net stream filestream

我有一个文本文件。多个进程可以同时尝试读取和编辑此文件。我对FileStream.Unlock()方法有疑问:

using System;
using System.IO;
using System.Text;

static class Program
{
    static void Main()
    {
        var fileName = @"c:\temp\data.txt";

        // Content of the 'c:\temp\data.txt' file:
        // Hello!
        // The magic number is 000. :)))
        // Good luck...

        using (var stream = new FileStream(fileName, FileMode.Open, 
            FileAccess.ReadWrite, FileShare.ReadWrite))
        {
            using(var reader = new StreamReader(stream))
            {
                var value = 0;
                Console.Write("New value [0-999]: ");
                while(int.TryParse(Console.ReadLine(), out value))
                {
                    var prevPosition = stream.Position;
                    stream.Position = 28;
                    var data = Encoding.UTF8.GetBytes(value.ToString());
                    try
                    {
                        stream.Lock(stream.Position, data.LongLength);
                        Console.WriteLine("Data locked. Press any key for continuation...");
               Console.ReadKey();
     stream.Write(data, 0, data.Length);
                        stream.Flush();
                        // I get the Exception here: The segment already unlocked.
                        stream.Unlock(stream.Position, data.LongLength);
                    }
                    catch(Exception ex)
                    {
                        Console.WriteLine("Error: {0}", ex.Message);
                    }
                    stream.Position = prevPosition;
                    Console.Write("New value: ");
                }
            }
        }
    }
}

为什么我的流在我自己执行之前已解锁?

2 个答案:

答案 0 :(得分:2)

原因是在您锁定文件(因为您写入文件)后stream.Position被提升,并且您使用stream.Position(现在不同)来解锁文件。结果 - 你试图解锁你锁定的相同范围。相反,请保存stream.Position

var position = stream.Position; // < save
stream.Lock(position, data.LongLength);
Console.WriteLine("Data locked. Press any key for continuation...");
stream.Write(data, 0, data.Length); // < this changes stream.Position, breaking your old logic
stream.Flush();
// I get the Exception here: 
// The blocking of the segment already taken off.
stream.Unlock(position, data.LongLength); // < now you unlock the same range

答案 1 :(得分:0)

不确定,但也许当你写时,Stream.Position会改变。