c# - 如何跨进程锁定/解锁文件?

标签 c# linux mono locking

在 Linux 上使用在 mono 上运行的 C#,注意下面的代码在 windows 上运行良好,可以跨进程锁定文件,但在 linux 上不能通过 mono (ubuntu 14.04)

new FileStream("myfile.lock",FileMode.OpenOrCreate,FileAccess.ReadWrite,FileShare.None);

网上查的,我应该可以用advisory lock

FileStream.Lock

然而,它不起作用。在 ubuntu 14.04 上用两个进程进行测试,它们都可以执行“FileStream.Lock(0, int.MaxValue)”。我希望后一个会失败,异常为 source code .

谁知道有什么解决办法吗?

最佳答案

从单声道邮件列表“http://mono.1490590.n4.nabble.com/File-Locking-td4663839.html”获取帮助

下面是“Edward Ned Harvey (mono)”的回答

Kinda sorta. The underlying issue is that OSX, Linux, and Windows all have different underlying file locking constructs, and then of course, there's some variability about even which filesystem is being used. I didn't thoroughly figure out all the answers for every OS or filesystem, and I don't know under which situations this will be good enough, but this is what I ended up using, works under the conditions we needed it to work:

using (var foo = new FileStream(filePath, FileMode.Open,FileAccess.ReadWrite, FileShare.None)) { // must include Write access in order to lock file 
    foo.Lock(0, 0); // 0,0 has special meaning to lock entire file regardless of length 
}

For windows, simply specifying the FileAccess and FileShare is good enough. For linux, at least ext4, files are concurrently readable regardless of what you specify for FileAccess and FileShare. The Lock() method does something of a soft-lock. It's not enforced by the OS, but at least all the situations we tried, other client apps honor the lock. Didn't look into it any deeper.

关于c# - 如何跨进程锁定/解锁文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35444470/

相关文章:

c# - 尽管已禁用,但验证仍在显示

c# - 尝试将数据从 WPF 应用程序发送到任何 Web 浏览器上的网页

c# - 如何优化 C# 异步调用

linux - Linux 上的 pthread_mutex_timedlock

linux - 在多个 Golang 程序之间传递配置值

c# - 将 UIImage 转换为字节数组

shell - 如何在 IronPython/Mono 中运行 OS shell 命令?

c# - 如何ReportProgress多个值?

linux - 如何在linux中使用iptables打开UDP端口

C# 计时器分辨率 : Linux (mono, dotnet 核心)与 Windows