I want to have an application that monitors a ceratain folder and show new images that appear in that folder. I successfully managed to detect new images using FileSystemWatcher
class, however I have a problem to display them. I have a following code:
public partial class MainWindow : Window
{
FileSystemWatcher watcher = new FileSystemWatcher();
public MainWindow()
{
InitializeComponent();
watcher.Path = "C:/Users/maciejt/Pictures";
watcher.Filter = "*.jpg";
watcher.NotifyFilter = NotifyFilters.LastAccess | NotifyFilters.LastWrite
| NotifyFilters.FileName | NotifyFilters.DirectoryName;
watcher.Created += new FileSystemEventHandler(OnCreated);
watcher.EnableRaisingEvents = true;
}
private void OnCreated(object source, FileSystemEventArgs e)
{
Console.WriteLine("File: " + e.FullPath + " " + e.ChangeType);
image.Dispatcher.Invoke(new Action(() => { image.Source = new BitmapImage(new Uri(e.FullPath)); }));
}
}
It works for some 10-20 creations of small (~100kB) images and 1-2 large (~4MB). Later it throws an exception that the image is used by another process. I also observed in the debugger, that memory used by the application increases drastically with every new image, just like previous images were not disposed.
What would be a correct way to create a BitmapImage
and show it in Image
control?
EDIT:
I have tried a solution suggested in a possible duplicate, however that still gives me the same exception, not even working once this time. Below the code after modification:
private void OnCreated(object source, FileSystemEventArgs e)
{
Console.WriteLine("File: " + e.FullPath + " " + e.ChangeType);
image.Dispatcher.Invoke(new Action(() => { image.Source = LoadBitmapImage(e.FullPath); }));
}
public static BitmapImage LoadBitmapImage(string fileName)
{
using (var stream = new FileStream(fileName, FileMode.Open))
{
var bitmapImage = new BitmapImage();
bitmapImage.BeginInit();
bitmapImage.CacheOption = BitmapCacheOption.OnLoad;
bitmapImage.StreamSource = stream;
bitmapImage.EndInit();
bitmapImage.Freeze();
return bitmapImage;
}
}