【问题标题】:Why my stream is unlocked before I do it myself?为什么我的直播在我自己做之前就被解锁了?
【发布时间】:2018-09-28 16:43:51
【问题描述】:

我有一个文本文件。多个进程可以同时尝试读取和编辑此文件。我对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: ");
                }
            }
        }
    }
}

为什么我的直播在我自己解锁之前就被解锁了?

【问题讨论】:

  • 顺便说一句,如果有多个进程作用于底层文件,Lock 是没有用的,它仅适用于当前进程中的线程。
  • @AlexK。不,你错了:msdn.microsoft.com/en-us/library/…
  • 旁注,UnLock 应该在 finally 块内
  • @HenkHolterman 你是对的。谢谢。

标签: c# .net stream filestream


【解决方案1】:

原因是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

【讨论】:

    【解决方案2】:

    不确定,但也许当您写入时,Stream.Position 会发生变化。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-06-04
      • 1970-01-01
      • 2016-02-25
      • 1970-01-01
      • 1970-01-01
      • 2019-05-31
      • 2023-03-20
      相关资源
      最近更新 更多