Reputation: 4652
In my application I scan images and creat a treeview and when I click on the name of file I show the image in imageViewer,
but when I use delete directory after that I clear the treeview and the imageviewer
treevImage.Nodes.Clear();
imageViewer.Image.Dispose();
imageViewer.Image = null;
Directory.Delete(localPath, true);
I got an exception that one image was used by another thread, the problem is that it is random, the first one or any other image!
The process cannot access the file 'image9.tif' because it is being used by another process.
Is there a way to know which part of my application uses that image?
Edit :
When I add
imageViewer.Dispose();
l'app delete the files without exception but when I scan again I got exception when show a new image in imageViewer
Object reference not set to an instance of an object.
Edit 2:
Exception do to dispose() was corrected by MikeNakis but now After I delete the directory I make a new scan and to show the new images in the imageViewer, after dispose() and new ; I can't see the new images for the new scan
Upvotes: 2
Views: 224
Reputation: 62015
Once you have disposed the imageViewer with imageViewer.Dispose();
you need to then re-create it with imageViewer = new ImageViewer();
.
Upvotes: 2
Reputation: 2986
I occasionally have to wait a few ms after closing and disposing a file before it is available for reading on the same thread - just as you describe above. I solved this by writing a method which wait until I had exclusive access to the file.
File.Open(path, FileMode.Open, FileAccess.Read, FileShare.None)
Remember to put a thread.sleep in that loop. If this locks up your program, you're forgetting to dispose something.
(I never investigated why this was required since the workaround was successful and has been in use for almost 10 year now. Could be a bug in my code, but since I was writing to the file before closing/disposing it I suspect that our anti-virus software placed a brief lock on the file)
Another solution is to prevent the image object locking the file at all. You can read the image file into a memory stream, and instantiate the image from it. Just ensure you do this right so that you don't end up copying the image around in memory more than neccessary.
Upvotes: 0