Removing a WPF Window Wallpaper

I had a problem with WPF when the window does not release the lock file in the background image file after closing, before another part of the application tries to write to the image.

So, as an example; I have a WPF application consisting of 3 windows, 1 “menu” and 2 others. Both windows are created ImageBrushusing BitmapImageas ImageSource(the same image).

Window A has a button that, when pressed, cycles through the available background images, copying them to the file used as the original ImageSource, and creating a new one ImageBrushand setting it Window.Backgroundin a new brush.

Window B just uses ImageBrushfor drawing Window.Background.

If window A starts, the backgrounds switch, close, and then window B starts, everything is in order.

If window B is started, closed, then window A starts and background synchronization is reset. When you try to switch the background is thrown IOException, because:

"The process cannot access the file" C: \ Backgrounds \ Background.png "because it is being used by another process.

So, Window B still holds onto that !? I tried to do GC.Collect(); GC.WaitForPendingFinalizers();to see if this problem fixes, but it is not.

+3
source share
2 answers

, , , XAML.

, BitmapImage , BitmapCacheOption:

BitmapImage img = new BitmapImage { CacheOption = BitmapCacheOption.OnLoad };
img.BeginInit();
img.UriSource = imageUrl;
img.EndInit();

<BitmapImage CacheOption="OnLoad" UriSource="..." />

, , FileStream, :

  • Uri, pack://Uri.
  • XAML
  • -, Uri . , .
+4

, , ?

BitmapImage img = new BitmapImage();
img.BeginInit();
img.UriSource = imageUrl;
img.EndInit();

; , :

BitmapImage img = new BitmapImage();
using (FileStream fs = File.OpenRead(imageFilePath)
{
    img.BeginInit();
    img.StreamSource = fs;
    img.EndInit();
}
+2

Source: https://habr.com/ru/post/1721701/


All Articles