【发布时间】: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