FileNotFoundException takes too long to throw, is there a way to shorten the timeout?

I have code that loads an image as follows:

using (var sourceImage = Image.FromFile(fullImagePath)) { return new Bitmap(sourceImage); } 

Sometimes the image will be incorrect or not expected, and System.IO.FileNotFoundException will be correctly selected. However, this exception often takes about 1 second. When my code captures several hundred images, and some of them are missing, this adds a significant portion of the time to the process.

Is there a way to speed up an exception if you need to throw it?

The only alternative I can come up with is to check if the first image exists, but this adds a few tens of milliseconds to each individual image sample, which is also not a good solution.

Explanation . An example of what fullImagePath contains:

 \\ImageSrv\secure\sites\2756\27074\760789\bthumb\1287.jpg 

In one directory there may be several hundred other images.

Conclusion Checking for the existence of files seems to be the best way.

+4
source share
2 answers
  • Prevent the exception yourself. Check if file exists instead of allowing Image.FromFile to crash and pass shenennigans exception
  • Store the cache in your memory to remove the need for additional calls to your hard drive.
  • If a situation is required, update the cache using FileSystemWatcher
+2
source

You can save a cache of file names that you periodically update through another stream. Then you can check this and immediately find out if the file exists (bypassing File.Exists service data)

Of course, this will not work if the files in the directory are constantly added / deleted.

0
source

All Articles