多站访问的文件锁定问题同时进行 [英] File lock problem for multi-station getting access at the same time

查看:54
本文介绍了多站访问的文件锁定问题同时进行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用文件流锁定文件:

I am using file stream to lock a file:

FileStream fs = File.Open(path,FileMode.Open,FileAccess.Read,FileShare.None)

发现问题:

当两站同时遇到这一点,它们都能够获取文件流,同时CanRead属性为true。一段时间后,他们将
更改为false,而文件流Handler将抛出异常女巫无法捕获。这似乎是一个僵局。 

请指教如何解决这个问题。 

推荐答案

如果您要打开文件进行阅读在2个不同的过程中,它们不应相互影响。无需担心共享问题。你唯一需要担心的是,如果其中一个试图读取而另一个试图写入
。现在编写代码的方式,其中一个进程将抛出异常,因为您明确地告诉操作系统,如果有其他人打开它然后失败。对于阅读,您不应该真的需要这样做。不要传递任何东西用于共享
,或者如果必须,则传递FileShare.Read以允许其他进程也读取它。这将消除共享问题。

If you're opening a file for reading in 2 different processes then they shouldn't impact each other. There is no need to worry about sharing issues. The only time you'd need to worry about this is if one of them tried to read while the other was trying to write. The way your code is written now, one of the processes will throw an exception because you're explicitly telling the OS that if anybody else has it open then fail. For a read you shouldn't really ever need to do that. Don't pass anything for sharing or, if you must, then pass FileShare.Read to allow other processes to read it as well. This will eliminate the sharing issue.

CanRead属性在创建实例时初始化,之后不会更改值。将属性设置为false的唯一方法是放置流。这很可能是这里发生的事情。它与
多个进程无关。您没有指定如何管理流的生命周期,但您的应用需要。只要流被主动引用,CanRead就不会改变。但是如果你没有保留对流的引用,那么在某些时候系统将释放
,如果你然后尝试访问CanRead,那么它将是错误的。如果您尝试访问任何其他方法,您将获得异常。您没有发布正在发生的异常。

The CanRead property is initialized when the instance is created and will not change values thereafter. The only way for the property to be set back to false is if the stream is disposed. That is most likely what is happening here. It has nothing to do with multiple processes running. You didn't specify how you're managing the lifetime of the stream but your app needs to. As long as the stream is actively referenced CanRead won't change. But if you don't keep a reference to the stream then at some point it'll get released by the system and if you then try to access CanRead then it'll be false. If you try to access any other method you'll get an exception. You didn't post the exception that is occurring.

Michael Taylor

http://www.michaeltaylorp3.net

Michael Taylor
http://www.michaeltaylorp3.net


这篇关于多站访问的文件锁定问题同时进行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆