NoWar
NoWar

Reputation: 37642

Update image file from parallel Task issue

I use this code to populate WPF Image Control.

string pathToImage = System.IO.Path.Combine(Settings.ContentFolderPath, file);

Image image = new Image();
BitmapImage src = new BitmapImage();
src.BeginInit();
src.UriSource = new Uri(pathToImage, UriKind.Absolute);
src.EndInit();
double ratio = src.Width / src.Height;
image.Source = src;
image.Stretch = Stretch.Uniform;
image.Height = marquee1.Height;
image.Width = marquee1.Height * ratio;
lstItems.Items.Add(image);

Also I have some parallel Task to update this image file.

But when I try to delete it I am getting the error: File is busy by other process you cannot delete this file.

How to resolve this issue?

Thank you!


UPDATES

So thank you all of you!

The final solution needs to implement

src.CacheOption = BitmapCacheOption.OnLoad;
src.CreateOptions = BitmapCreateOptions.IgnoreImageCache;

the working code looks like

Image image = new Image();

BitmapImage src = new BitmapImage();
src.BeginInit();
src.CacheOption = BitmapCacheOption.OnLoad;
src.CreateOptions = BitmapCreateOptions.IgnoreImageCache;
src.UriSource = new Uri(pathToImage, UriKind.Absolute);
src.EndInit();
double ratio = src.Width / src.Height;

image.Source = src;
image.Stretch = Stretch.Uniform;
image.Height = marquee1.Height;
image.Width = marquee1.Height * ratio;
lstItems.Items.Add(image);
result = image.Width;

Upvotes: 2

Views: 286

Answers (3)

Chris Shain
Chris Shain

Reputation: 51369

Set the CacheOption property of the BitmapImage to BitmapCacheOption.OnLoad. This will cause it to load the image into memory and close the original file, which should allow you to delete it.

Upvotes: 1

GETah
GETah

Reputation: 21449

MSND BitmapImage.CacheOption says:

Set the CacheOption to BitmapCacheOption.OnLoad if you wish to close a stream used to create the BitmapImage.

Set the BitmapImage.CacheOption to OnLoad:

BitmapImage src = new BitmapImage();
src.BeginInit();
src.UriSource = new Uri(pathToImage, UriKind.Absolute);
src.CacheOption = BitmapCacheOption.OnLoad;
src.EndInit();

Upvotes: 4

Adam Mihalcin
Adam Mihalcin

Reputation: 14478

Also I have some parallel Task to update this image file ... when I try to delete it I am getting the error

In general, you can't delete a Windows file while a process is using it. The consumer Windows FAQs include this page to describe this restriction. And as MSDN describes, File.Delete will refuse to delete a file that's in use.

Upvotes: 0

Related Questions