Why is File.Open so expensive?

I have the following code:

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;
}

Since this program runs on 2 computers that access the same folder for collecting files, it throws an exception when a file is opened, and then moves to the next file in its list.

When I open the application on 2 PCs at the same time, the first computer manages to open the image, and the second does not. I show 4 images on the screen right away, but some debugs show that the second computer takes 10.5 seconds to crash when opening 4 files before it finds one that it can open.

Why is it so expensive and what can I do to speed it up?

: , , , PC1 1,2,3,4, - 5,6,7,8, 1,2,3,4. , , , .

+3
4

, , - , .net framework, , -/ . , .

+3

FileAccess.ReadWrite (, , ). , , FileShare.None ( ).

, . , , , . , , :

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.
+4

, , (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

Have you tried experimenting with these flow properties? You can minimize the timeout if nothing else:

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

0
source

All Articles