为什么File.Open如此昂贵?

时间:2011-06-16 12:15:09

标签: c# .net file exception file-io

我有以下代码:

try
{
    string fileName = imageQueue.Dequeue();
    FileStream fileStream = File.Open(
        fileName, FileMode.Open, FileAccess.ReadWrite, FileShare.None);
    Bitmap bitmap = new Bitmap(fileStream);
    Image picture = (Image)bitmap;
    pb.Tag = fileName;
    pb.Image = picture;
    return true;
}
catch (Exception ex)
{
    errorCount++;
    //If another PC has this image open it will error
    return false;
}

因为这个程序在2台PC上运行,访问同一个文件夹以选择文件,所以当一个文件打开然后移动到其列表中的下一个文件时,它会抛出异常。

当我在2台PC上同时打开应用程序时,第一台PC设法打开图像,但第二台PC没有。我在屏幕上一次显示4张图像,但是进行一些调试显示第二台PC在打开4个文件之前需要10.5秒才能失败,然后才发现它可以打开。

为什么这么贵,我该怎么做才能加快速度呢?

更新:我给它独占访问权限,因为我希望应用程序显示唯一的图像,因此PC1显示图像1,2,3,4和PC显示5,6,7,8因为它不能得到1,2,3,4。然后,一旦我完成了文件流,并且在最后可能的时刻,我也会释放文件流,以防止其他应用程序尝试打开它。

4 个答案:

答案 0 :(得分:4)

您正在以FileAccess.ReadWrite打开文件(您似乎没有写作)。您告诉它您不想共享文件FileShare.None,(因此第一台获取文件的PC获胜)。

此外,您永远不会关闭流。因此,获取文件的PC首先会保留它,直到垃圾收集器为您关闭流。当您将流包装在using块中时,文件将自动关闭:

using (FileStream fileStream = File.Open(fileName, FileMode.Open, FileAccess.ReadWrite, FileShare.None)
{
    // Do stuff with the filestream
}
// The stream will be closed when the closing brace is passed.

答案 1 :(得分:3)

我无法肯定地回答,但我最好的建议是,在.net框架类或文件系统中,系统中的某些内容正在实现文件共享失败时的超时/重试机制。这可以解释您报告的过度延迟。

答案 2 :(得分:3)

编辑后

由于您希望它们被锁定,您可以考虑滚动一个轻量级数据库(sqllite,xml等),您可以使用该数据库将文件标记为“正在使用”。然后在该方法中,您将检查它是否正在使用中。这将消除在尝试打开锁定文件时必须等待File.Open超时。

<强>原始

我想我应该回答而不是评论......

try
{
    string fileName = imageQueue.Dequeue();
    using( FileStream fileStream = File.Open( fileName, FileMode.Open, FileAccess.Read, FileShare.Read) )
    {
        Bitmap bitmap = new Bitmap(fileStream);
        Image picture = (Image)bitmap;
        pb.Tag = fileName;
        pb.Image = picture;
    }

    return true;
}
catch (Exception ex)
{
    errorCount++;
    //If another PC has this image open it will error
    return false;
}

答案 3 :(得分:0)

您是否尝试过尝试使用这些流属性?如果没有别的话,您可以最小化超时:

http://msdn.microsoft.com/en-us/library/470w48b4.aspx